How to Extend a Standard .NET Class With Your Own Methods

Sometimes you may be annoyed by writing a separate class to perform something on a .NET class that can not be inherited from. And even if it can, you would still face the trouble of having your fields and properties declared as of your own class. Wouldn’t it be nice to just have that one method that Microsoft hasn’t considered important enough to include in the class, or maybe it’s something you use all over the place in your solution but it’d be so much easier to just call it on an object? Well, welcome to extension methods! Say, you have a solution where you have to output a comma-separated string of Ids given an IEnumerable list. Wouldn’t it be nice to say something like

var output = myList.ToEnuList();

There is a way to do that, and it is easy.
Create a static class in your project and then create an extension method, the rest is all the same. Let’s give it a try:

public static class MyExtensionMethods
{
	public static string ToEnuList(this IEnumerable list)
	{
		var s = "";
		foreach (var l in list)
		{
			s += "," + l;
		}
		if (s.Length > 0) { s = s.Substring(1); }
	}
}

The this keyword in front of the list parameter and the fact that this is a static method tells the compiler that this is an extension method, therefore extending the IEnumerable interface. It basically says that our “this” is not a parameter but rather the object we are calling the method on, much like you would use “this” within a class.
Having our list as IEnumerable, we also ensure that whether it’s a List or Dictionary or Array or [] or what else, all of them are going to have this new method.
Include a file with this code in your project and you’ll see that IntelliSense will have it there. Here’s what you get by calling this:

var list = new List<int> { 5,3,2,4 };
Console.Write(list.ToEnuList());	// output: "5,3,2,4"
var arr = new object[] { "1", "a", 5, "___", new object() };
Console.Write(list.ToEnuList());	// output: "1,a,5,___,Object"

A simple concept, really 🙂
Now, if we go back to our foreach loop, read the next post to see how it can be done with LINQ.

This entry was posted in C# and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *