Thursday, May 14, 2015

4. Extension Methods

Extension Method = static method of a static class that can be invoked by using the instance method syntax.


e.g.:

public static class MyAwesomeExtensions
{
       public static int WordCount(this string input)
       {
           return input.Split(' ').Count();
       }
 
 
       public static string Concatenate(this string input, string toAdd)
       {
           return input + toAdd;
       }
 
       public static bool IsNullOrEmpty(this string s)
       {
           return string.IsNullOrEmpty(s);
       }
}


Then, you can use (in the same project or in a project referencing this class):


string s = "This is a test";
int wordCount = s.WordCount();
var something = s.Concatenate(" yeah");

The first parameter of the function, the one with the "this" keyword, specifies what type are you extending.

More on Extension Methods - MSDN

No comments:

Post a Comment