20 January 2014

C# Extension Methods

Hi All,

Lets see whats the extension method in C# and whats the main use of it.  Sometime we want to add a method in existing class.  This class can be from the .net library or any third party class.  To do so we generally extends the existing class in our new class and then compile it and use that new class.

Like in c# library class - "string" does not have any such method to count if we want such method we have to design our own method.  Remember you can not inherit the "string" class as its sealed.

static class MyClass
{
  public static int WordCount(string line)
  {
      line = line.Trim();
      return line.Split(' ').Length;
  }
}


now you have to call this method like -

int n = MyClass.WordCount("String whatever we want to pass");


but if we want to merge this method with existing c# library string class?  but as we dont have source code of string class we can not edit the source code write?

Extension method do this job.  Using the extension method we can add the method in compiled class without needing source code, so that you can call your own method like the previous existing method in string class.

string str = "string whatever we want to pass";
int n = str.WordCount();


to add an extension method to existing class you just need to class a static class and static method like we created earlier.  The only change we required in passing parameter we need to add the "this" keyword.

static class MyClass
{
    public static int WordCount( this string line)
    {
        line = line.Trim();
        return line.Split(' ').Length;
    }
    
    public static int WordCountStartsWith( this string line, char c)
    {
        int result = 0;
        line = line.Trim();
        
        var word = from wrd in line.Split(' ')
                   where wrd.First() == c
                   select wrd;
        result = word.Count();

        return result;
    }

    public static int WordCountContains( this string line, string str)
    {
        int result = 0;
        line = line.Trim();

        var word = from wrd in line.Split(' ')
                   where wrd.Contains(str)
                   select wrd;
        result = word.Count();

        return result;
    }
}


Now to call these method we can just use the object of string class.

This is the beauty of the extension method, we do not need to recompile the parent class(in this case string class).  We just need to remember when want to design an extension method -
  1. static class
  2. static method
  3. this keyword just before the passing parameter class, whose extension we want. 
Download Sample


See we are getting our own three extension method on string class.

string line = "string value or line whose word we want to count";
int n = line.WordCountContains("nt");

Happy Coding and Blogging.. !! :)

No comments:

Post a Comment