Extention methods allow us to add new functionality to existing classes without modifying existing implimentation.
- An extension method is a static method
- It must have this keyword associated with classname
- The classname should be the first parameter in the parameter list
Extension Method Syntax:
Definition of an extension method:
First, let's create a new static class called
StringExtensions
. The class name is not important, but it's a common convention to use the name of the type being extended followed by "Extensions". Inside this class, we'll define a static method called Reverse
:public static class StringExtensions
{
public static string Reverse(this string input)
{
char[] chars = input.ToCharArray();
Array.Reverse(chars);
return new string(chars);
}
}
usage:
class Program
{
static void Main(string[] args)
{
string example = "Hello, World!";
string reversed = example.Reverse();
Console.WriteLine(reversed); // !dlroW ,olleH
}
}
Extension methods look and behave like instance methods, but there are a few important differences to keep in mind:
- Extension methods cannot access private members of the extended type.
- They also do not participate in inheritance or polymorphism.
- You cannot override an existing method with an extension method.
If the extended type has a method with the same signature as an extension method, the instance method will always take precedence. Extension methods are only called when there is no matching instance method.
Comments
Post a Comment