Extension Method is new feature introduced with C# 3.0. Extension method allow the
user to add a new method to the existing types without having to create new derived
type, or modify the original type. They are nothing more than a static method, but
they are called in a way similar to any of the existing instance method.
The main reason for introducing extension method was to support huge list
of LINQ query operators. This does not mean that without extension method LINQ was
not possible, but without the same it would not have been so much a breeze
as it is currently. GroupBy, OrderBy, SingleOrDefault, FirstOrDefault are some of
the most common extension method used in LINQ.
Below is an example of simple extension method that is used to convert he given
string into a decimal value and return the same with n digits(count specified in
the second paramete) after decimal places.
public static class
public static decimal ConvertToDecimal(this string inputValue,
decimaloutValue = 0;
out outValue) ?
decimal.Round(outValue,digitafterDecimal) : outValue;
The first parameter of the method ConvertToDecimal start with
this followed by the datatype. By this it implies the type of data for
which this method will act like an instance method.
After that rest of the parameter are normal parameter and need to be supplied while
calling the extension method. This is all that is required to write an extension
method. Visual studio provide a unique symbol that helps unique identify the extension
method in the list of other methods.
Some Interesting fact:
When IL code is generated by compiler, it translate the call to extension method
into a normal call on a static method. So don’t be confused that principle of encapsulation
is being violated.
Make sure to include the proper namespace to see the your custom extension method
or inbuilt ones. For example, you need to add System.Linq to see the standard extension
method associated with the same.
Extension method are a way to extend the class or an interface, but this no
way means that they can override them. If you have a method in an interface or a
class with same signature as that of your extension method, these method will take
precedence over the extension method and will be called. And at this point you really
need to be cautious as VS does not give any warning or error about which method
will be used.
Find below the complete code:
static void Main(string
stringvalue = "234.567";
value.ConvertToDecimal(1); // returns number with one digit
value.ConvertToDecimal(2); // returns number with two digit
/// Extension Method to convert a given string to number withgiven number
/// of digits after decimal
/// <paramname="inputValue">Type for whichextension method will
act a instance method</param>
/// <paramname="digitafterDecimal">Parameterindicating the number
of digit after decimal</param>
/// <returns>decimal value</returns>
returndecimal.TryParse(inputValue, out outValue)
Happy Coding :)