What is Extension Method in C#


C# 3.0 introduced new features Extension Methods. Extension methods allow you to extend an existing type with new functionality, without modify old class.

If you want check that specific string is number or string. Usually we use the approach to create a utility class with one method which take string and check that it is number or not. like this:
public class Utility
{
    public static bool IsNumber(string val)
    {
        float output;
        return float.TryParse(val, out output);
    }
}


string valueCheck = "4";
if (Utility.IsNumber(valueCheck))
    Console.WriteLine("Value is number");
else
    Console.WriteLine("Value is not a valid number ");


You need to create a class and call like this.

In Extension Methods, we can 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 FirstExtensionMethods
{
    public static bool IsNumber(this string val)
    {
        float output;
        return float.TryParse(val, out output);
    }
}


Main difference between Extension Methods and Other static method is that “this” keyword in the parameter of methods. Compiler identity this is an extension method for the string class, and that's actually all you need to create an extension method. You can call the IsNumber() method directly on strings, like this:

string valueCheck = "4";
if (valueCheck.IsNumber())
    Console.WriteLine("Value is number");
else
    Console.WriteLine("Value is not a valid number ");


Comments