Class extension in. net

Source: Internet
Author: User
Tags valid email address

Summary:. Net has two methods for class Extension: one is extension method and the other is partial classification;

Extension Method:

In C #. net, you can customize extension classes, that is, to extend some ready-made classes or classes without source code.

The extension method allows you to extend an existing type and add its method without inheriting it or re-compiling it. Unlike the object write assistant method, the extension method can be a part of the object itself. An extension method is a static method defined in a static class and must have a parameter pointing to the type object attached to the method.

For example, if we want to verify whether a string (which already exists and has no source code) is a valid email address, we can compile a method, enter it as a string, and return true or false. Now we can use the extension method as follows:

Public static class myextensions {

Public static bool isvalidemailaddress (this string s ){

RegEx = new RegEx (@ "^ [w-.] + @ ([w-] +.) + [w-] {2, 4} $ ");

Return RegEx. ismatch (s );



We define a static class with a static method. Note that the static method has a this keyword before the parameter type string, which tells the compiler that this special extension method will be added to the string type object. So we can call this member method in string:

Using myextensions;


String email = request. querystring ["email"];

If (email. isvalidemailaddress ()){




Of course, in addition to the method in this example, if you add partial before the class, you can directly name the same class in another file to add the method you need.

For example:

Namespace PC
Partial Class {}

Namespace PC
Partial Class {}

These two classes are actually a class. In this way, the automatically generated code is separated from the self-compiled code. Easy code control.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.