[Solved] extension method for List with both constraints class and struct [closed]


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;
}

2

solved extension method for List with both constraints class and struct [closed]