Understanding Extension Methods in .Net

AramT
51.6K 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'

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
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content