Generic Extension Methods

suggest change

Just like other methods, extension methods can use generics. For example:

static class Extensions
{
    public static bool HasMoreThanThreeElements<T>(this IEnumerable<T> enumerable)
    {
        return enumerable.Take(4).Count() > 3;
    }
}

and calling it would be like:

IEnumerable<int> numbers = new List<int> {1,2,3,4,5,6};
var hasMoreThanThreeElements = numbers.HasMoreThanThreeElements();

View Demo

Likewise for multiple Type Arguments:

public static TU GenericExt<T, TU>(this T obj)
{
     TU ret = default(TU);
     // do some stuff with obj
     return ret;
}

Calling it would be like:

IEnumerable<int> numbers = new List<int> {1,2,3,4,5,6};
var result = numbers.GenericExt<IEnumerable<int>,String>();

View Demo

You can also create extension methods for partially bound types in multi generic types:

class MyType<T1, T2>
{
}

static class Extensions
{
    public static void Example<T>(this MyType<int, T> test)
    {        
    }
}

Calling it would be like:

MyType<int, string> t = new MyType<int, string>();
t.Example();

View Demo

You can also specify type constraints with where :

public static bool IsDefault<T>(this T obj) where T : struct, IEquatable<T>
{
     return EqualityComparer<T>.Default.Equals(obj, default(T));
}

Calling code:

int number = 5;
var IsDefault = number.IsDefault();

View Demo

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents