"Extention Methods" are new feature in C# 3.0 and above. We could define them as static methods that extend existing classes.
If we wanted to do something like that in the past we had to derive from the selected class and extend it with whatever we wanted. But what if that class is a sealed class? Extention methods come in just for that.
Lets say we need to reverse a string. Before we had extention methods we would probably have something like this:
public class StringOperations
{
public static string ReverseString(string str)
{
string i = string.Empty;
foreach (char c in str)
{
i = i.Insert(0, c.ToString());
}
return i;
}
}
And we would use it like this:
static void Main(string[] args)
{
string g = StringOperations.ReverseString("abcd");
}
Well now we don’t have to. We can actually attach the ReversString method to the string object! Here’s how:
namespace System
{
public static class Extentions
{
//notice that we use this as the parameter.
public static string Reverse(this string str)
{
string i = string.Empty;
foreach (char c in str)
{
i = i.Insert(0, c.ToString());
}
return i;
}
}
}
We have just extended the System namespace with a method called Reverse.
Now we can reverse a string like this:
string gg = ("abcd").Reverse();
Great!!!
No comments:
Post a Comment