CyberSecurity // Azure // Frontend // Svelte // Cloud Native // Software // CyberSecurity // Azure // Frontend // Svelte // Cloud Native // Software

Csharp extension methods

Cover for Csharp extension methods

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'.

// CSHARP //

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.

// CSHARP //

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:

// CSHARP //

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