Extension methods are a feature of C# 3.0.Extension method allow you to add new method to the existing class without modifying the code ,recompiling or modifying the original code.you can write extension methods for interfaces/abstract class.Extension method is nothing but the Visitor pattern.
Visitor Pattern:-
Visitor pattern allows us to change the class structure without changing the actual class. Its way of separating the logic and algorithm from the current data structure. Due to this you can add new logic to the current data structure without altering the structure. Second you can alter the structure without touching the logic
To write an extension method, you do the following
Define a public static class.
Define a public static method in the class where the first argument is the data type for which you want the extension method
Use the this keyword on the first argument to your public static method. The this keyword denotes the method as an extension method
Example 1
using System;
public class MyClass
{
public int IntField;
public MyClass(int arg)
{
IntField = arg;
}
}
public static class MyClassExtension
{
public static void PrintIt(this MyClass arg)
{
Console.WriteLine("IntField:{0}", arg.IntField);
}
public static void Main()
{
MyClass mc = new MyClass(10);
mc.PrintIt();
Console.ReadKey();
}
}
Example 2
using System;
namespace ExtensionMethods
{
public static class ExtensionsClass
{
public static string Reverse(this String strReverse)
{
char[] charArray = new char[strReverse.Length];
int len = strReverse.Length - 1;
for (int i = 0; i <= len; i++)
{
charArray[i] = strReverse[len - i];
}
return new string(charArray);
}
public static void Main()
{
string str = "Hi How r u?";
String strss= str.Reverse();
}
}
}