Understanding Extension Methods in .Net

AramT
2,047 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

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
1
10
11
12
13
14
15
16
// {...}
public static bool IsNullOrEmpty<T>(this IEnumerable<T> Source)
{
if (Source == null) return true;
return !Source.Any();
}
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content