What are extension methods?
Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.
How to use extension methods?
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.
Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.
Program to show how to use extension methods
Create a project Class Library as:

using System;
using System.Text;
namespace ClassLibExtMethod
{
public class Class1
{
public string Display()
{
return (“I m in Display”);
}
public string Print()
{
return (“I m in Print”);
}
}
}
Now create a new project File -> New -> Project

Add the reference of the previously created class library in this project.

Code as following and use the ClassLibExtMEthod.dll in your namespace:
using System;
using System.Text;
using ClassLibExtMethod;
namespace ExtensionMethod1
{
public static class XX
{
public static void NewMethod(this Class1 ob)
{
Console.WriteLine(“Hello I m extended method”);
}
}
class Program
{
static void Main(string[] args)
{
Class1 ob = new Class1();
string str = ob.Display();
console.write(str);
string strmad= ob.Print();
console.write(strmad);
ob.NewMethod();
Console.ReadKey();
}
}
}
You can see the extension method with an arrow (different from normal method sign), as they were instance methods on the extended type. See the figure below:

Output of the above program

Benefits of extension methods
- Extension methods allow existing classes to be extended without relying on inheritance or having to change the class’s source code.
- If the class is sealed than there in no concept of extending its functionality. For this a new concept is introduced i.e. extension methods.
- This feature is important for all developers
especially if you would like to use the dynamism of the C# enhancements to be taken place in your classes design.
More Code Snippet to extension expansion methods
using System;
using System.Text;
namespace ExtensionMethod2
{
public static class ExtMetClass
{
public static int IntegerExtension(this string str)
{
return Int32.Parse(str);
}
}
class Program
{
static void Main(string[] args)
{
string str = “123456″;
int num = str.IntegerExtension();
Console.WriteLine(“The output using extension method: {0}”, num);
Console.ReadLine();
}
}
}
In the above program we have used extension method IntegerExtension() to convert string to numeric type
Important points while using extension methods:
- An extension method must be defined in a top-level static class.
- An extension method with the same name and signature as an instance method will not be called.
- Extension methods cannot be used to override existing methods.
- The concept of extension methods cannot be applied to fields, properties or events.
- Overuse of extension methods is not good style of programming.
Extension methods allow existing classes to be extended without relying on inheritance or having to change the class’s source code. This means that if you want to add some methods into the existing String class you can do it quite easily. Here’s a couple of rules to consider when deciding on whether or not to use extension methods:
- Extension methods cannot be used to override existing methods
- An extension method with the same name and signature as an instance method will not be called
- The concept of extension methods cannot be applied to fields, properties or events
- Use extension methods sparingly….overuse can be a bad thing!
Here’s an example of creating an extension method in C# that adds a RemoveNonNumeric() method to the String class. Notice that the class is defined as static as well as the extension method itself. The “this” keyword in the parameter signature tells the compiler to add the extension method to the String class since “string” follows the keyword.
namespace StringExtensions
{
public static class StringExtensionsClass
{
public static string RemoveNonNumeric(this string s)
{
MatchCollection col = Regex.Matches(s, "[0-9]");
StringBuilder sb = new StringBuilder();
foreach (Match m in col)
sb.Append(m.Value);
return sb.ToString();
}
}
Here’s an example of how the extension method can be used. You’ll see that the namespace for the extension method class is imported. From there, the compiler treats the RemoveNonNumeric() method as if it was originally part of the standard System.String class.
using StringExtensions; .... string phone = "123-123-1234"; string newPhone = phone.RemoveNonNumeric();
Update: Although the overall point of the post was to simply show how to create extension methods, Andrex posted a more efficient way to remove non-numeric characters for those that may actually need that specific functionality (I’ll admit I was just throwing something out there
). Thanks for commenting Andrex!
public static string RemoveNonNumeric(this string s)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i++)
if (Char.IsNumber(s[i]))
sb.Append(s[i]);
return sb.ToString();
}
Update 2: Richard posted the following method which is potentially even faster according to his tests. We’re kind of pulling hairs here, but it’s useful for “anyone who agonizes over every wasted millisecond” as he mentions in the comments (I’m not one of those people
). I’m thinking I should start a “How would you refactor this code” series. Could be kind of fun.
public static string RemoveNonNumeric(this string s)
{
if (!string.IsNullOrEmpty(s))
{
char[] result = new char[s.Length];
int resultIndex = 0;
foreach (char c in s)
{
if (char.IsNumber(c))
result[resultIndex++] = c;
}
if (0 == resultIndex)
s = string.Empty;
else if (result.Length != resultIndex)
s = new string(result, 0, resultIndex);
}
return s;
}
ref:http://www.c-sharpcorner.com/UploadFile/puranindia/ExtensionMethodsCSharp308312009025943AM/ExtensionMethodsCSharp3.aspx
http://weblogs.asp.net/dwahlin/archive/2008/01/25/c-3-0-features-extension-methods.aspx
