According to definition: "Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type"
Example:
namespace ExtensionMethods
{
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
And use it:
string s = "Hello Extension Methods";
int i = s.WordCount();
Note the following:
- Extensions should be defined in a static class
- Extensions should be defined in a static methods
- First parameter should be "this {class} {var}"
No comments:
Post a Comment