Introduction
This is a new feature in C# 3.0 that helps to extend existing classes like .NET core classes which cannot be extended. You may need to add functionality without extending the class, or recompiling the existing class or modifying the existing method.
Few Points on ExtensionMethods
- It is a new feature of C# 3.0.
- Extension method enables to add new methods to existing type. It does not need creation of derived type to existing type, modifying the original type or recompiling the original type.
- It provides the ability to the programmer to add new methods to existing type.
- It can be used to add new methods to existing .NET core classes.
- It is defined as a
static
method but called with the syntax of an instance method.
- If there is a member method in type class with the same name of
Extension
method, then member method will get precedence over Extension
method.
For example: Show
method is a member method of Message
class. So if there is any extension method called Show
on type Message
class that is created, always Show
member method will get precedence over Show
extension method for the type Message
.
Using the Code
Compiler signature of Extension
method is as follows:
static class Extensions
{
public static IEnumerable<T> Where<T>(this IEnumerable<T> sequence,
Predicate<T> predicate)
{
foreach (T item in sequence)
{
if (predicate(item))
{
yield return item;
}
}
}
}
- The method is
static
.
- The first parameter is decorated with modifier “
this
”.
- The first parameter is called as Instance Parameter.
- A compile time error will be encountered to use this modifer with any other parameter than instance parameter.
- No other modifers like
ref
, out
, etc. are allowed with “this
” modifer or instance parameter.
- The instance parameter cannot be a pointer type.
- The method is
public
.
- The instance parameter cannot have the type of the type parameter. The below is not possible:
public static int Obj<T> (this T param)
Restrictions on Extension Methods
- It could only access
public
members of the target type.
- If an
Extension
method conflicts with a member method of target type, always member method gets invoked instead of Extension
method.
Implementation and Calling of Extension Method
- Define a
static
visible class to contain Extension
method.
- Implement the
Extension
method as static
method.
- The first parameter of method specifies the type method works on.
- The first parameter must be preceded by “
this
” modifer.
- At the client code, add namespace of
Extension
method with using
directive.
Examples of Extension Method
In the first example, I will add an Extension
method to the existing String
class. This Extension
method will remove all the vowels from the string
.
Modify the class with modifiers public
and static
of the class extensionmethodcontainer
.
Add an Extension
method with the below signature. The first parameter String
specifies that this is an Extension
method on the type String
.
public static String RemoveVowel(this String s)
The full code to remove vowel from input string
is written in the Extension
method.
ExtensionMethodContainer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExtensionMethodSample
{
public static class extensionmethodcontainer
{
public static String RemoveVowel(this String s)
{
string[] vowels = new string[] { "A", "E", "I", "O", "U" };
if (string.IsNullOrEmpty(s))
return string.Empty;
List<char> chars = new List<char>(s.ToCharArray());
for (int i = chars.Count - 1; i >= 0; i--)
{
for (int j = 0; j < vowels.Length; j++)
{
if (chars[i].ToString().ToLower() == vowels[j].ToLower())
chars.RemoveAt(i);
}
}
return new string(chars.ToArray());
}
}
}
Client code is in the Main
class.
In the main
class, user inputs the string
and RemoveVowel Extension
method is called on the input string
to remove vowel from the string
.
Note
- Here both
Extension
method and client are in the same namespace, so there is no need to include namespace of the Extension
method.
Extension
method is called as any other member method.
resultString = str.RemoveVowel();
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExtensionMethodSample
{
class Program
{
static void Main(string[] args)
{
String resultString;
Console.WriteLine("Enter Input String to Remove all Vowel using " +
"Extension Method \n");
String str = Console.ReadLine();
Console.WriteLine("After Removing Vowel Input String is \n");
resultString = str.RemoveVowel();
Console.WriteLine(resultString);
Console.ReadKey();
}
}
}
History
- 12th June, 2009: Initial post