# Understanding Extension Methods in .Net

AramT
16.1K 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
// { autofold
using System.Collections.Generic;
using System.Linq;
namespace Extensions
{
public static class GenericsExtensions
{
// }
public static bool IsNullOrEmpty<T>(this IEnumerable<T> Source)
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
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.