C # Extension Methods

Source: Internet
Author: User

In C #, extension methods enable you to add methods to existing class without creating a new derived class.

Extension Methods Requirements:

    1. Define a static class to contain extension method. This class must is visible to client code.
    2. Implement the extension method like a static method, but add "this" modifier before the first parameter.
    3. The first parameter specifies the type, this extension method operates on.
1 usingSystem.Globalization;2 usingSystem.Threading;3 4 namespaceLibrary5 {6      Public Static classstringextensions7     {8         //static Method9         //Public static String Converttotitlecase (this string source)Ten         //extension Method One          Public Static stringConverttotitlecase ( This stringsource) A         { -CultureInfo CultureInfo =Thread.CurrentThread.CurrentCulture; -TextInfo TextInfo =Cultureinfo.textinfo; the  -             returntextinfo.totitlecase (source); -         } -     } +}

Extension Methods Call:

Call extension method, like extension method, is a instance method on the type.

1 namespaceLibrary_simple2 {3     //Import extension Method namespace4     usingLibrary;5     class Program6     {7         Static voidMain (string[] args)8         {9             stringSource ="The return of the king";Ten             stringextected ="The Return of the King"; One  A             //static Method -             //string result = Stringextensions.converttotitlecase (source); -             //extension Method the             stringresult =source. Converttotitlecase (); -  - assert.isnotnull (result); - assert.areequal (expected, result); +         } -     } +}

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.