How to implement and use Extension Method in C# with examples

C# provides a  very useful feature to extend the feature of an existing type without requiring the source code of original data type or permission of author who created the original type. Use of extension method is very common and every application creates one or more extension methods based on thier custom requirement. We will see some of the easiest example of Extension methods and see how it's works.

Creating Extension methods is very straight forward and it's like creating a static class with static method and the first parameter of the method will have "this" keyword of C# language.

public static class StringExtensions
{
public static string Truncate(this string value, int length)
{
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), "Length must be >= 0");
else
return value.Substring(0, System.Math.Min(value.Length, length));
}
}


In the above example we can see that StringExtensions is a static class with a static method named Truncate ​with first parameter have this ​keyword before the data type string so basically this is a string extension method which is extending the feature of string data type and providing the truncate feature.

Methods.png


Once Extension method is created in the application we can C# compiler gives us intelli sense for the new extension method as well.

I have written the below unit test for the Truncate method to validate the same.

[TestMethod()]
public void TruncateTest()
{
var testString = "ABCD1234";
var truncateVal = testString;
Assert.AreEqual(truncateVal,"AB");
}


Above is the simple String Extension method and we can create any number of Extension method based on our requirements.

We can create extension method based  on pre defined data type of C# language like int, String, Decimal, Dictionary etc..


Let's create another extension method based on String data type which will return numbers only from a given string.

public static string NumbersOnly(this string sText)
{
const string sNumbers = "0123456789";
StringBuilder sRes = new StringBuilder();

if (!string.IsNullOrEmpty(sText))
{
for (int i = 0; i < sText.Length; i++)
{
string sChar = sText.Substring(i, 1);
if (sNumbers.Contains(sChar))
{
sRes.Append(sChar);
}
}
}
return sRes.ToString();
}


Unit Test to validate NumbersOnly Extension Method

[TestMethod()]
public void NumbersOnlyTest()
{
var testString = "ABCD1234";
var numberResult = testString.NumbersOnly();
Assert.AreEqual(
numberResult,"1234");
}


Hope you understood the Extension methods in C#

Share This Post

Linkedin
Fb Share
Twitter Share
Reddit Share

Support Me

Buy Me A Coffee