In C #, extension methods enable you to add methods to existing class without creating a new derived class.
Extension Methods Requirements:
- Define a static class to contain extension method. This class must is visible to client code.
- Implement the extension method like a static method, but add "this" modifier before the first parameter.
- 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