Extension methods are a way to add methods to a class
without changing its source code or adding it into a derived class.
Creating extension
methods example
Define extension method –
public static class StringExtensions
{
public static string Reduce(this String str, int numOfWords)
{
if (numOfWords <= 0)
return str;
var numWords = str.Split(' ');
if (numOfWords >= numWords.Length)
return str;
return String.Join(" ", numWords.Take(numOfWords));
}
}
Shorten is an extension class on the String class. Adding as
above, we were able to add the new method to String Class without actually
changing the class or deriving from it. Above method shortens the size of a
sentence/string.
Using the extension methods – as normal –
static void Main(string[] args)
{
string post = "sjdf sdljsd sdilsdflj sdfsdf sopsfsd regkjdfg sdkhgfsdfk...";
var shorte = post.Reduce(4);
Console.WriteLine("Reduced String is>>" + shorte);
}
Using an already
defined System extension method
static void Main(string[] args)
{
string post = "sjdf sdljsd sdilsdflj sdfsdf sopsfsd regkjdfg sdkhgfsdfk...";
var shorte = post.Reduce(4);
Console.WriteLine("Reduced String is>>" + shorte);
IEnumerable<int> numbers = new List<int>() {12,34,34,12,22};
Console.WriteLine("Max is >>" + numbers.Max());
}
In above example, we use the extension method defined in
IEnumerable interface. Most of the times we will just use the extension methods
as opposed to creating them.