- This is a new feature in C# 3.0
- Extension methods allow an existing type to be extended with new methods without altering the definition of the original type.
- An extension method is a static method of a static class, where the this modifier is applied to the first parameter.
- The type of the first parameter will be the type that is extended.
Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Extention_Methods
{
class Program
{
static void Main(string[] args)
{
string language = "malayalam";
Console.WriteLine(language.MyCustomMethod());
Console.ReadLine();
}
}
static class StringUtils
{
public static int MyCustomMethod(this string input)
{
return (input.Length);
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Extention_Methods
{
class Program
{
static void Main(string[] args)
{
string language = "malayalam";
Console.WriteLine(language.MyCustomMethod());
Console.ReadLine();
}
}
static class StringUtils
{
public static int MyCustomMethod(this string input)
{
return (input.Length);
}
}
}
Ref : here