Understanding Extension Methods in .Net

AramT
1,439 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

To illustrate more about the usage of the extension methods in .Net, we will write a simple program that defines an extension method that reverses any given string.

The below code widget displays a simple runnable example that includes 2 tabs of C# code:

The first tab has the reverse extension method implementation.

And the second tab is the unit test that will show how to use that extension method and will assert that our extension method will actually reverse the given input string.

Note in the using section we have included the Extensions namespace.

You can press on Run button to build the application, in browser, and see the test result:

So let's see if our reverse extension method will actually reverse the word 'coding' into 'gnidoc'
1
9
10
11
12
13
14
// {...}
public static string Reverse(this string input)
{
if (string.IsNullOrEmpty(input)) return "";
return new string(input.ToCharArray().Reverse().ToArray());
}
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Note that even though the Extension method has 1 parameter defined, we still call the method without passing any arguments.

This is due the fact that, as mentioned above, the first parameter defined in the extension method is the type that has to be identical to the class or datatype, that is being extended.

Extension method example with one additional parameter

Now let's write another example that shows how to use extension methods with an additional parameter. In this case, the extension method will have 2 parameters on its definition.

The below is a simple function to calculate the value after tax of a given amount in float, we will define the tax percentage in the method's parameter, which we will pass it when calling the extension method:

After you run this sample, the unit test will verify that the final amount includes the calculated tax value by apply the provided tax percentage
1
2
3
4
5
6
7
8
9
10
11
12
13
·namespace Extensions
{
public static class FloatExtensions
{
public static float CalculateValueAfterTax(this float currentValue, float taxPercentage)
{
if (taxPercentage < 0 || taxPercentage > 100)
return currentValue;
float taxRatio = (1 + taxPercentage / 100);
return currentValue * taxRatio;
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content