I want a method to only work on types which implement the /, +, -, * operators. Is there any "clean" way to do this?
views:
77answers:
4You can define constraints on Type Parameters. So you can require T to implement an interface:
public static class Classy
{
public static void Extension<T>(this IEnumerable<T> Ninjas)
where T : IMathStuff
{
}
}
This requires all T to implement IMathStuff. Now, if you can't fit the operators into the interface IMathStuff, you can leave the interface blank as a Marker Interface and only apply it to classes that do implement the operators.
This kind of assumes you're working with all custom classes and not the built-in types. It's a workaround for something that isn't exactly supported.
There is not a clean way to do this. You will need to implement IEnumberable<int>, IEnumberable<float>... etc
Not at compile-time. You'd have to use reflection, I think.
A lot of those are value types such as int and long, "where T : struct" but there is no interface or base type that is common to them.
This would require an interface, such as IArithmetic.
Unfortunately, this doens't work currently. This is a highly requested feature, however.
There are some workarounds, usually requiring working with a second generic parameter, but most wouldn't work with IEnumerator<T>
.