Back to overview

CSharp extension methods

▼ Post information

Author Jef Meijvis Publish date 16/10/2021
Title CSharp extension methods Id 1
Source 001-csharp-extension-methods.md Render timestamp Dec 06, 2023, 06:08:30 AM (GMT+1)
Views 31 Tags CSharp
Author Jef Meijvis
Publish date 16/10/2021
Title CSharp extension methods
Id 1
Source 001-csharp-extension-methods.md
Render timestamp Dec 06, 2023, 06:08:30 AM (GMT+1)
Views 31
Tags CSharp
opengraph

▼ Table of contents

Share this post:

Extension methods?

As a programmer, extension methods are a great tool to have in your toolbox! They allow you to extend the functionality of an existing type without having to modify the type. This can be useful in cases were you don't have access to the type, or when you want to increase modularity by keeping some functionality out of the main class.

The most well known extension methods are those of the Linq library. These methods add additional functionality to classes that implement the IEnumerable interface!

Lets demonstrate extension methods by expanding the String class For this example we want to see if a string contains the world apple. The regular way of doing this is by creating a method that takes the string as input, and check wether or not it contains the fixed string 'apple'.

Code snippet

1
    string juice = "Applejuice";
2
    string smoothie = "Banana smoothie";
3
    string desert = "Pie with apples and bananas on top";
4

5
    bool FoodContainsApple(string food)
6
    {
7
        return food.ToLower().Contains("apple");
8
    }
9

10
    Console.WriteLine(FoodContainsApple(juice));    // True
11
    Console.WriteLine(FoodContainsApple(smoothie)); // False
12
    Console.WriteLine(FoodContainsApple(desert));   // True

This works, and for such a basic example as this, it might suffice to do it this way. But let's try and get the same results using extension methods this time around. We start out by creating a new class, extensions.cs. Make sure that the class is static. We implement the static method ContainsApple() containing the same logic as before. Note however the 'this' keyword before the input argument. This will allow use to use the method as if it was a method contained inside of the string class.

A realistic example

For the next example, we want to make an extension method that allows us to select a random element from an array. We try to create this as generic as possible, by extending the IEnumerable interface.

Code snippet

1
public static T GetRandom<T>(this IEnumerable<T> inputEnumerable)
2
{
3
    int index = new Random().Next(0, inputEnumerable.Count());
4
    return inputEnumerable.ElementAt(index);
5
}

We implement the following generic extension method that selects a random element from the collection. This allows us to hide the random selection logic, and contain it in the Extensions.cs file. We can now use this method by once again including the correct namespace, and invoking the method on, for example, an array of strings:

Code snippet

1
using ExtensionMethodsBlogpost;
2

3
string[] fruits = { "Apple", "Banana", "Orange" };
4

5
// Logs one of the elements of the collection
6
Console.WriteLine(fruits.GetRandom())

This was a quick look at extension methods, and how they can make life easier when working with classes where you don't have access to the actual implementation!

Further reading

Back to top