Can anyone tell me if there is a way with generics to limit a generic type argument T
to only:
Int16
Int32
This limitation affected me when I tried to overload operators for generic types; since there was no "INumeric" constraint, and for a bevy of other reasons the good people on stackoverflow are happy to provide, operations cannot be defined on generic types.
I wanted something like
public struct Foo
{
public T Value{ get; private set; }
public static Foo operator +(Foo LHS, Foo RHS)
{
return new Foo { Value = LHS.Value + RHS.Value; };
}
}
I have worked around this issue using .net4 dynamic runtime typing.
public struct Foo
{
public T Value { get; private set; }
public static Foo operator +(Foo LHS, Foo RHS)
{
return new Foo { Value = LHS.Value + (dynamic)RHS.Value };
}
}
The two things about using dynamic
are