Generic Extension Methods C# with Example



Generic Extension Methods C# with Example

Just like other methods, extension methods can use generics. For example: 
static class Extensions 
{ 
public static bool HasMoreThanThreeElements(this IEnumerable enumerable) 
{ 
return enumerable.Take(4).Count() > 3; 
} 
 

} 
and calling it would be like: 
IEnumerable numbers = new List {1,2,3,4,5,6}; 
var hasMoreThanThreeElements = numbers.HasMoreThanThreeElements(); 
View Demo 
Likewise for multiple Type Arguments: 
public static TU GenericExt(this T obj) 
{ 
TU ret = default(TU); 
// do some stuff with obj 
return ret; 
} 
Calling it would be like: 
IEnumerable numbers = new List {1,2,3,4,5,6}; 
var result = numbers.GenericExt,String>(); 
View Demo 
You can also create extension methods for partially bound types in multi generic types: 
class MyType 
{ 
} 
static class Extensions 
{ 
public static void Example(this MyType test) 
{ 
} 
} 
Calling it would be like: 
MyType t = new MyType(); 
t.Example(); 
View Demo 
You can also specify type constraints with where : 
public static bool IsDefault(this T obj) where T : struct, IEquatable 
{ 
return EqualityComparer.Default.Equals(obj, default(T)); 
} 
Calling code: 
int number = 5; 
var IsDefault = number.IsDefault(); 
 

View Demo 

0 Comment's

Comment Form

Submit Comment