C # Extension methods

Source: Internet
Author: User

1. The extension method enables you to "add" methods to an existing type without creating a new derived type, recompiling, or otherwise modifying the original type. An extension method is a special static method, but it can be called just like an instance method on an extended type. for client code written in C # and Visual Basic, there is no significant difference between calling extension methods and calling methods that are actually defined in the type.

2. extension methods are defined as static methods, but they are invoked through the instance method syntax. Their first argument specifies which type the method acts on, and the parameter is prefixed with the This modifier. extension methods are only in scope when you explicitly import namespaces into the source code using a using directive.

3. in code, you can invoke the extension method using the instance method syntax. However, the compiler-generated intermediate language (IL) translates the code into a call to a static method. Therefore, the encapsulation principle is not really violated. In fact, extension methods cannot access private variables in the types they extend.

Called Under the same namespace

namespacestringextension{classProgram {Static voidMain (string[] args) {            inttestnum=0;            Console.WriteLine (Testnum.tostrings ());        Console.read (); }    }     Public Static classExtension { Public Static stringTostrings ( This inti) {returni.tostring (); }    }}

The namespace under which the using extension method is to be used without a namespace, and the extension method and extension class should be public

C # Extension methods

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.