tags:

views:

70

answers:

3

Hello,

I need to calculate in a generic class. I#ve found some solutions like here: http://stackoverflow.com/questions/147646/solution-for-overloaded-operator-constraint-in-net-generics, but i need to calucate T with double. is it possible to cast T to double? So i can write code like this:

class Myclass<T>{
  T value;
  public double Half() {
    return  i.value  / 2;
  }
}

Myclass<int> i = new Myclass<int>();
double x = i.Half();

Thanks!

+1  A: 

Geenrics and operators don't mix. In 4.0 you can use dynamic for this; until then, MiscUtil has DivideInt32 which should work perfectly for cases like:

T half = Operator.DivideInt32(value, 2);

However, speciailizing in double won't really work well. You might as well start with double (instead of T) in that case. You could use ToString and Parse, but that isn't neither robust nor efficient.

Edit - there is also Convert, so you could try:

return Operator.Convert<T,double>(value) / 2;
Marc Gravell
+1  A: 

The answer in the question you've linked to is correct: you can't really do this in C#.

The best you can do is to re-implement the Half method once for each possible type:

public double Half() {
    if (typeof(T) == typeof(double))
        return HalfDouble();
    else if (typeof(T) == typeof(int))
        return HalfInt();
    else if (typeof(T) == typeof(decimal))
        return HalfDecimal();
    // etc.
}
Tim Robinson
A: 

What you could to is make the class constructor accept a parameter of type Func<T,double> that converts your T to a double. In the double Half() function, you call this functor and divide the result by 2.

For more information on this technique, read Bill Wagner's 'Effective C#'.

jdv