C #4.0 new feature learning (2)-Expansion Method

Source: Internet
Author: User

The extension method is actually the syntax feature introduced in C #3.0 (I am out ). By using the extension method, you can add a method to an existing type "dynamic" without creating a new derived type or modifying the source code of the original type.

There are the following primitive types:

Class mymath
{
Public int add (int A, int B)
{
Return A + B;
}
}

Add "Extension Method"

Static class mymathextend
{
Public static int sub (this mymath math, int A, int B)
{
Return A-B;
}
}

Call the added "Extension Method ":

Mymath math = new mymath ();
Console. writeline (math. sub (5, 3 ));

We can see that the original class mymath is not modified, but a new method sub is added for it.

Key points for using the extension method:

(1) The extension method must be static and put in a non-generic static class. So the above mymathextend class adds the modifier static, And the sub method is also static;

(2) The first parameter of the extension method must have the this keyword before it specifies the type of object to which the extension method will be "appended.

You can also add extension methods for existing classes in the. NET class library. For example, add an extension method for the string class in. Net:

Static class stringextend
{
Public static string append (this string S, string Str)
{
Stringbuilder strb = new stringbuilder (s );
Strb. append (STR );
Return strb. tostring ();
}
}

Call the extension method added for the string class:

String S = "AA ";
Console. writeline (S. append ("BB "));

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: info-contact@alibabacloud.com 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.