Loading [Contrib]/a11y/accessibility-menu.js

Understanding Extension Methods in .Net


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'
// { autofold
using System.Linq;
namespace Extensions
public static class StringExtensions
// }
public static string Reverse(this string input)

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
·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;
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
Online Participants