Wednesday, 13 April 2016

What is Extension Method in C#?


Extension methods are new feature in C# 3.0. An extension method enables us to add methods to existing types without creating a new derived type, recompiling, or modify the original types. In other words it extends the functionality of an existing type in .NET. An extension method is a static method to the existing static class. We call an extension method in the same general way; there is no difference in calling.
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, like this:

public class UtilClass
{
    public static bool IsNumeric(string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}

Now you could check a string by executing a line of code like this:

string test = "6";
if (UtilClass.IsNumeric(test))
    Console.WriteLine("Yes");
else
    Console.WriteLine("No");

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 MyExtensionMethods
{
    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 IsNumeric() method directly on strings, like this:

string test = "4";
if (test.IsNumeric())
    Console.WriteLine("Yes");
else
    Console.WriteLine("No");

Click to view feature and properties of Extension Methods.



No comments:

Post a Comment

Featured post

What is SharePoint?

Microsoft SharePoint is an extensible platform that provides a range of products that can help organizations with solution for a variety...