You can specify a constraint for T
that it must be a struct, and perhaps that it implements IConvertable, and then use Convert
.
public class NumberContainer
where T : struct, IConvertible
{
public T ValueA { get; private set; }
public T ValueB { get; private set; }
public T Total {
get
{
// do type checking here, then:
return (T)Convert.ChangeType(
Convert.ToDouble((object)ValueA) +
Convert.ToDouble((object)ValueB), typeof(T));
}
}
}
However, there's no way with generics to guarantee that T is an integer or floating type at compile time. You can check it at runtime, though, and throw an exception.