Extension Methods in C#

Chidozie Ogbo
Afrivelle Engineering
2 min readApr 7, 2019

Extension methods are like exotic cars. The very cool stuff you have but never get to use. Extension methods are my favourite part of C# and I think I might be the only one.

What are Extension Methods?

Extension methods are like the name implies, methods that extend a particular class without having to modify the class itself. It’s most importance in cases where you deal with already compiled classes like String, Integer and IEnumerable. It basically helps you abstract actions that you always like to perform on instances of this classes.

For eg:

C# Strings have a `ToUpper` and `ToLower` method. These methods are as their name implies, for changing a string to uppercase/lowercase respectively. But what if you want to change a string to Sentence case or Pascal case, what do you do?

Your first thought might be to write an helper method that does that ie.

public class Helper{
public static string ConvertToSentenceCase(string word){
............
return word;
}
}
......Helper.ConverToSentenceCase("Obi IS A boy");

While this works, this introduces a new class Helper and is not very elegant.

Then, walks in extension methods… DRUM ROLLS!!!!

A basic extension method has 3 major components.

  • A static class
  • A static method
  • A 1st parameter same type with the class or struct being extend.

Example

To recreate the example above using extension methods, see the below example.

String Extension example

From the above, you can see that when using an extension method, the first parameter is ignored. This first parameter takes in the current value of the class or struct being extended.

Just look at the elegance.

Also, remember that to use the extensions, you have to import the namespace of the extension class. The great thing about it is that you can make a library of commonly used extensions and simply import them into each of your projects.

Fun Fact

The majority of the amazing LINQ’s work is to provide extension methods to the IEnumerable<T> interface. That means that you can call any LINQ method on any object that implements IEnumerable<T>. You can even create your own classes that implement IEnumerable<T>, and those classes will instantly "inherit" all LINQ functionality!

And there you go, another reason to love C#.

--

--

Chidozie Ogbo
Afrivelle Engineering

Web/Mobile Developer, UX Enthusiast and Habitual Thinker.