Extension Methods Feature in C# with Simple Example

Monday, April 27, 2015 0 Comments A+ a-


Extension methods are special type of methods which were introduced in C# 3.0. They are used to extend the functionality of  any existing type in .Net.Using extension method we can add new methods to a class/type without modifying original source code of  Type, recompiling, or creating a new derived type.

Normally when we use linq standard query operators that add query functionality to the existing IEnumerable and System.Collections.Generic.IEnumerable<T> types. For using the standard query operators,first bring them in scope by writing using System.Linq in the code file.

Now you can call for example GroupBy,OrderBy etc like instance methods on any type that implement IEnumerable<T>

According to MSDN :

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. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

Syntax of writing Extension Method :

As extension method is a special method, it is defined little differently than normal method.Here is the points to be noted when writing extension method:

  1. It should be a static method.
  2. It should be written in a static class.
  3. its first parameter starts with this keyword followed by type parameter
  4. Extension method should be in the same namespace otherwise you will need to inculde namespace of the class with a using statement. 

Simple Example:

We can write extension method for any existing type in our code.Most of the time we write extension method for types that we cannot modify which are built-in in the .Net Framework.

I will make a simple extension method on string type to convert string to integer.

public static class StringExtensions
 public static int ToInt32(this string value)
  int result;
  if (int.TryParse(value, out result))
   return result;

  return 0;

and we can use it to convert string to integer if string contains numeric value in. We can call it this way:

public class Program
 public static void Main()

You can see running example in  this fiddle

Coursera - Hundreds of Specializations and courses in business, computer science, data science, and more