Extension methods are used for adding methods to existing classes and types.
These are special kind of Static methods but they are called as if they were instance methods.
Extension methods are defined in static class and methods are also static.
E.g. if we want to count the number of words in a string then we can have an extension method that counts the character in its base string
namespace ExtensionMethods
{
public static class Extensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
So WordCount is our Extension Method that operates on string. To use this method we must have to include its namespace in the class where we are going to use it.
using ExtensionMethods;
Now within that class our method can be called like this :
string str = "Hello Extension Methods";
int i = str.WordCount();
You may go to https://msdn.microsoft.com/en-IN/library/bb383977.aspx for reference
0 Comment(s)