Extension Methods in C#

 Extension Methods in C#


Introduction:

To understand the concept of extension methods, we should understand the problem that extension method solves. 

Problem extension methods solve:


You are working on a project in a financial domain. To the UI, you want to return a string in a currency format. i.e. you don't return 1000 but return $1000 (not an excellent design though!).

So, every time when you have to return the currency formatted string, you will append $ (or whatever) to the string and return. 

Then you decide to write a helper class and move the logic of appending the $ to the helper method.

This may solve the problem. But it would be better to extend the existing String class to include a new method. i.e. String class should also have a new method, say appendCurrency().

string myMoney = "1000";

myMoney.appendCurrency();

appendCurrency() is called as though it is a member of string class.

We can achieve this using extension method.


Syntax:

To create an extension method,
  • Create a static class
  • Inside this static class, create a static method. This method is an extension method. 
  • The extension method should take class name that is extending as it's first parameter. But we should also pass "this " along with the class name.

The syntax is as below:

public static class MyExtension
{
    public static fakeRetValue myExtensionMethod(this <classNameToBeExtended> param)
    {
        return fakeReturn:
    }
}

Example:

For the example, described in the problem statement, the extension method implementation is as below: (this is a very simple example!)


string myMoney = "1000";

string withCurrency = myMoney.appendCurrency();

Console.WriteLine(withCurrency);


public static class stringExtension

{

    public static string appendCurrency(this string str)

    {

        return "$" + str;

    }

}