Monday, November 3, 2014

Create custom extension method in C#

This tutorial explains about how to create your own custom extension method in C# language.

1. Create a static class that's going to have the extension method.
2. Implement the extension method as static method.
3.  The first parameter of the extension method defines which data type going to be extended and must be preceded with 'this' modifier.
4. Import the namespace which has extension method class.
5. Now the method can be extended by putting DOT after the variable like .ToString()

Example:
Lets create the extension methods (RemoveSpace() and RemoveNumber()) for removing numbers and space from the string.

Image 1: Extension method class




Image 2: Accessing extension methods




Image 3:Removes the numbers from string




Image 4:Removes the spaces from string