C#: Extension Methods in .NET
_____________________________________________________________________________________________________________________________________________________________________________________
Sometimes there is a need to add customized/ user defined methods to existing datatypes.
If we write String s1 and then put a dot after s1, we get a list of methods pre-defined such as Aggregate<>, All<>, Average<> etc.
With extension methods, we can write out our own method that can be used with existing datatypes as an extension.
Example
Step 1: Create a Console Application
Step 2: Create an ExtensionClass as
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/* Class to display Extension Method */
namespace DeeptendraSpace
{
public static class ExtensionClass
{
//**********//Extension Method//**************//
//Sample Extension Method 1
public static string ShowMethod(this string val)
{
return "Hello :" + val;
}
public static void AddMethod(this int x, int y)
{
Console.WriteLine(x + y);
}
}
}
Step3: In main method, implement your datatype extension method in the following way:
class Program
{
static void Main(string[] args)
{
String msg = "Deep";
Console.WriteLine("//********Extension Methods**********//");
Console.WriteLine(msg.ShowMethod()); // Calling Extension Method1 msg.ShowMethod()
int a, b;
a = 1;
b = 2;
a.AddMethod(b); //Calling Extension Method2 a.AddMethod(b)
Console.ReadKey();
}
}
Clearly we can see that the string msg, and integer a are calling extension methods from the ExtensionClass.