Press "Enter" to skip to content

How to create extension methods in C#

Extension methods are a way to have a function that can be used by all objects of a specific datatype or interface. They “extend” the functionality of object, without needing to alter the class.

public static class MyExtensionMethods
{
	public static string ToLeetCode(this string text)
	{
		return text.Replace("A", "@").Replace("E", "3")
			.Replace("I", "1").Replace("O", "0");
	}
	
	public static bool None<T>(this IEnumerable<T> elements, Func<T, bool> func)
	{
		return !elements.Any(func.Invoke);
	}
}
void Main()
{
	string value = "ANEXTENSIONMETHOD";
	string leetValue = value.ToLeetCode();
	Console.WriteLine(leetValue);
	
	List<int> numbers = new List<int> { 1, 4, 0, 5 };
	bool notAnyEqualZero = !numbers.Any(n => n == 0); // LINQ
	Console.WriteLine(notAnyEqualZero);
	
	bool allNotEqualZero = numbers.All(n => n != 0); // LINQ
	Console.WriteLine(allNotEqualZero);
	
	bool noneEqualZero = numbers.None(n => n == 0); // ExtensionMethod
	Console.WriteLine(noneEqualZero);
}

Creating extension methods

On lines 1-13, we have the class that holds our extension methods. Extension methods must be in a static class.

The class is named MyExtensionMethods, but it can be any name.

The extension methods are the ToLeetCode function that starts line 3 and the None function that starts on line 9. Both these functions are static – another requirement for extension methods.

For extension methods, the first parameter isn’t just the datatype and parameter name. The parameter in ToLeetCode doesn’t say “string text” – it says “this string text”. This first parameter is the datatype of object you can use the extension method on.

So, the ToLeetCode extension method will work for string objects. The None extension method has “this IEnumerable<T>”, so it can be used on any type of generic list or collection.

Inside the extension method functions, it’s just a typical function.

The three components of extension method are:

  1. It must be in a static class
  2. It must be a static function
  3. The first parameter has a “this” before the datatype. This identifies which type of objects you can use the extension method on.

Visibility of extension methods

Be aware that the code that’s trying to use an extension method needs to be able to see the extension methods.

So, in this case, anything that wants to use ToLeetCode or None extension methods would need to be able to see the MyExtensionMethods class and the ToLeetCode or None functions.

If the MyExtensionMethods class was in the same project as the objects trying to use these extension methods, the class and functions could be internal. But if MyExtensionMethods is in a separate project, the class and functions would need to be public, so they could be used by objects in a different project.

Using extension methods

On lines 15-30, there is a Main function to test the extension methods.

On lines 17-19, we create a “value” string variable. On line 18, we create a string “leetValue” variable and set it equal to “value.ToLeetCode()”. So, the “value” variable is passed into the ToLeetCode extension method, which converts the string and returns it, to be put into “leetValue”.

On lines 21-29, we use the None extension method.

First, on line 21, we create a list with the values 1, 4, 0, and 5.

Let’s say we want to know if the list does not contain any zeroes in it. We could use LINQ to check the items, like we do on lines 22 and 25. However, those both use a “!” in them for a Boolean “not”. In longer Boolean statements, “not”s can make the statement more difficult to understand. So, I often create a “None” extension method to encapsulate/hide the “!”.

Because the “numbers” variable is a list of integers, it meets the condition of being IEnumerable<T>. So, the None extension method can be used on it.

    Leave a Reply

    Your email address will not be published.

    This site uses Akismet to reduce spam. Learn how your comment data is processed.