I want to write extension for List<MyClass>
and List<int>
, List<string>
, and other types.
I tried to write this code:
public static int MyMethod<T>(this List<T> list) where T : struct where T : class
{
int result = //do something
return result;
}
As there´s no type that is neither a class nor a struct, applying both constraints to your member is redundant. Thus you can simply omit it completely, making your method work on any T
.
public static int MyMethod<T>(this List<T> list)
{
int result = //do something
return result;
}
Apart from this you can of course add multiple constraints to a method, e.g. this:
public void DoSomething<T>() where T: class, new() { /* ... */ }
which would make this method exist for reference-types with a parameterless constructor.
EDIT: when you have some specific types in mind, you should consider to create two methods instead, as you can´t do much for both integers and strings. So make two methods:
public static int MyMethodForInt(this List<string> list)
{
int result = //do something
return result;
}
public static int MyMethodForString(this List<int> list)
{
int result = //do something
return result;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments