Generic Extension Methods
suggest changeJust 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();
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>();
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();
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();
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents