Using C# Extension Methods

C# provides a powerful feature called extension methods that allow you to extend classes with new functionality without the need to modify the original class. This means you can extend such fundamental classes such as C#’s generic List collection class.

Throughout the years I have used a number of very useful extension methods that have proved very useful in many different projects.

In this tutorial, I will show you how to setup extension methods and demonstrate extending the List<T> and string class.

The first thing to be aware is that extension methods need to be in a static class. So, it makes sense to create a dedicated static class called ExtensionMethods.

See below…

using System;

namespace intermittentbug.DAL.Objects
{
    public static class ExtensionMethods
    {
         // place you Extension Methods here...
    }
}

The next thing to note regarding extension methods is that you must refer to the type you are extending as the first or only parameter.

Below is an example of a simple string class extension that can be called to trim() and ToLower() a string.

/// <summary>
/// Used to trim and set toLower()
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static String TrimAndLower(this String source)
{
    String srcStr = source.Trim().ToLower();
    return srcStr;
}

As I am extending the string class, the parameter I’m referring to is referenced as “this type variableName”

The convention I use is the variable name “source”.

This can be invoked like so…

[TestMethod]
public void TestTrimAndLower()
{
	string TestStr = "   TesTER  ";
	TestStr = TestStr.TrimAndLower();

	Assert.IsTrue(TestStr == "tester");
}

a slightly more advanced example, this method will capitalise the first letter of a string if its character length is greater than 3, otherwise it will capitalise all the letters. It also replaces a forward slash with a dash

/// <summary>
/// Capitalize the first letter of each word in the string
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static String CapitaliseFirstLetter(this String source)
{
	string returnStr = String.Empty;
	TextInfo TextInfo = new CultureInfo("en-GB", false).TextInfo;

	if (source.Length > 3)
	{
		source = source.ToLower().Trim();
		string capitalized = TextInfo.ToTitleCase(source);
		returnStr = capitalized;
	}
	else
	{
		returnStr = source.ToUpper();
	}

	// Remove any invalid chars
	return returnStr.Replace("/", "-");
}

This can be invoked like this...

[TestMethod]
public void TestCapitaliseFirstLetter()
{
	string TestStr_1 = "hello world";
	TestStr_1 = TestStr_1.CapitaliseFirstLetter();

	Assert.IsTrue(TestStr_1 == "Hello World");

	string TestStr_2 = "abc";
	TestStr_2 = TestStr_2.CapitaliseFirstLetter();

	Assert.IsTrue(TestStr_2 == "ABC");

	string TestStr_3 = "//hello/world//";
	TestStr_3 = TestStr_3.CapitaliseFirstLetter();

	Assert.IsTrue(TestStr_3 == "--Hello-World--");
}

Now to look at the List<T> class. Below is a Randomiser that will rearrange any List<T> object in a random order.

/// <summary>
/// Randomize a generic list, using a guid as the random indexer
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static IEnumerable<T> Randomize<T>(this IEnumerable<T> source)
{
	return source.OrderBy<T, Guid>((item) => Guid.NewGuid());
}

The List<T> class inherits the Ienumerable<T> interface so by extending that I get the benefit of this extention method to all objects that inherit from this interface. Below is a Randomiser I have used in many different projects. It will rearrange any List<T> object into a new random order.

[TestMethod]
public void TestRandomize()
{
	List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	List<int> RandomNumbers = new List<int>();

	RandomNumbers.AddRange(numbers.Randomize());

	//RandomNumbers = {3, 8, 6, 1 ....}
}

I will be posting more useful extention methods as useful tips.


JGilmartin Profile Image

JGilmartin

Technical Architect at Pinewood Technologies

Rating: 2890

C# Expert

Offline


Tutorial Statistics
  • Views: 368
  • Comments: 0
  • Author: JGilmartin (2890)
  • Date: 18/11/2016 17:41
Tags
C# .NET

© 2016 - 2018 - IntermittentBug