For an example, take the String class. This calss already has some methods for string manipulation like Split(), Trim(), .... Suppose we would like to add a new feature to the String class, like GetWordCount() so we could use it like this:
string str = "The new feature";
int words = str.GetWordCount();
Note that we have not created a new type. We are using the same old String class but with a new member method. We can achieve this by extension method.
static int GetWordCount(this string s)This method can be inside any class. The only thing matters is in what namespace the method is. If the GetWordCount method is in a namespace called MyExtensions, you can load the extension by adding the using directive like:
{
//
//Word count logic goes here
//
return count;
}
using MyExtensions;
So the String class will appear to have an extra method called GetWordCount whenever you use this namespace.
Refer to MSDN for better in-depth article.
No comments:
Post a Comment