Friday, May 31, 2013

LINQ 02- Extension Methods

Extension method is a way to add methods to existing types without inheritance. It is actually a virtual implementation of static methods.

For example, we may frequently want to get the Right n characters from string. We cannot inherit string data type as it is a sealed type. Even if we have a non sealed type, it would be difficult to include the right method to existing objects.

Simplest way would be adding a static method which receives a String and a length parameter, and returns string of right n characters.

public class StringMethods{

    public static string Right(string s, int n) {
        return s.Substring(s.Length - n);
    }

}

Calling this method would be easier like,

String s = “Muthukrishnan”;

String t = StringMethods.Right(s, 5); // Will return “shnan”

 

Extension method makes this easier for better readability.

To convert the right static method to extension method, we have to prefix this keyword to the first parameter which marks it as the calling object.

public class StringMethods{

    public static string Right(this string s, int n) {
        return s.Substring(s.Length - n);
    }

}

With this, we can call the Right method with a simple and familiar syntax.

String s = “Muthukrishnan”;

String t = s.Right(5); // Will return “shnan”

 

Note: To make the Extension methods to a code, the namespace or extension class should be imported.

No comments:

Post a Comment