Extension Method in C#

Definition

An extension method extends a class without creating a new derived class or modifying the original class. Let's create an application named MyExtensionMethod to learn how to use extension methods.

Example of Extension method

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyExtensionMethod
{
    public static class MyClass
    {  
    public static int MyExtensionMethod(this string Number)
    {
        return Int32.Parse(Number);
    }
    public static int MyStaticMethod(string Number)
    {
        return Int32.Parse(Number);
    }
    }
class MainClass
{
    public static void Main(string[] args)
    {
    string Number="100";
    int ext = Number.MyExtensionMethod();
    Console.WriteLine("the output from MyExtensionMethod()");
    Console.WriteLine(ext);
    int stat = MyClass.MyStaticMethod(Number);
    Console.WriteLine("");
    Console.WriteLine("The Output from MyStaticMethod()");
    Console.WriteLine(stat);
    Console.Write("\nPress ENTER to quit...");
    Console.ReadLine();
    }
}
}

We have created two methods, MyExtensionMethod() and MyStaticMethod(). The MyExtensionMethod() method is an extension method, which has the this keyword before its string type argument. Number; whereas, the MyStaticMethod() static method does not have the this keyword in its argument declaration. While calling the MyExtensionMethod() method, we have not passed any argument; whereas, in MyStaticMethod() method calling, we have passed the Number argument.

Output of Extension method

The Output from MyEntensionMethod()
100
            
The Output from MyStaticMethod()
100

Press ENTER to quit...


Write a comment


Name Email Message