Monday, June 20, 2016

Extension Methods

Extension Methods are used to add new behaviors of existing type without altering.
An Extension method is a static method of a static class that can be invoked using instance of method syntax.
In extension method “this” keyword is used with the first parameter and the type of the first parameter will be the type that is extended by the extension method.
At compile time an extension method call is translated into an ordinary static method.

A simple Extension Method Example


1.    //defining extension method
2.    public static class MyExtensions
3.    {
4.     public static int WordCount(this String str)
5.     {
6.     return str.Split(new char[] { ' ', '.', ',' }).Length;
7.     }
8.    } 
9.     
10. class Program
11. {
12.  public static void Main()
13.  {
14.  string s = "Dot Net Tricks Extension Method Example";
15.  
16.  //calling extension method
17.  int i = s.WordCount();
18.  
19.  Console.WriteLine(i);
20.  }
21. }
22. //output:
23. 6

No comments:

Post a Comment