Back
Close

Understanding Extension Methods in .Net

AramT
50.3K views

As mentioned previously, an extension method can be defined to extend generic classes or data type (of type T), you can normally write an extension method that can apply for a generic type.

The below method will check if the provided generic collection, that implements the IEnumerable interface, is null or empty, this can be useful whenever you have many collections objects of the generic type (T) that you are not sure if they are null or empty (size = 0) , so in order to avoid doing the standard collection == null || collection.size == 0 check on each collection object, you can simply call this extension method naturally and it will do the job for you.

Check the below example and run it to see how amazing it is to use the extension methods with generics

If you see the last 2 lines of our unit test which has the nullList, you might think that it will throw a null reference exception at runtime, because we are trying to access a method on a null reference object since we are calling the extension method using the method syntax, however, at runtime the IL or the intermediate language will translate the code to a call to the static method and thus will work normally.

To learn more about generic programming, check my interactive tutorial on tech.io about C# Generics

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io