Friday, July 6, 2012

Extension Methods (C# Programming)

Another cool feature of C# is Extension Methods. They allow you to extend an existing type with new functionality, without having to sub-class or recompile the old type. For instance, you might like to know whether a certain string was a number or not. The usual approach would be to define a function and then call it each time, and once you got a whole lot of those kind of functions, you would put them together in a utility class.However, with Extension Methods, you can actually extend the String class to support this directly. You do it by defining a static class, with a set of static methods that will be your library of extension methods. Here is an example:

public static class Helpers
{
    public static bool isNumber(this object inputvalue)
    {
        if (inputvalue == null) return false;
        Regex isnumber = new Regex("[^0-9]");
        return !isnumber.IsMatch(inputvalue.ToString());
    }

    public static bool isNumeric(this string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}
    

The only thing that separates this from any other static method, is the "this" keyword in the parameter section of the method. It tells the compiler that this is an extension method for the string class, and that's actually all you need to create an extension method. Now, you can call the isNumber() method directly on strings, like this:

     string test = "4";
     if (test.isNumber())
      Console.WriteLine("Yes");
    else
      Console.WriteLine("No");
    
    
Ref:


No comments:

Post a Comment