0

I am trying to create a Generic class to handle float and doubles. I need to perform computation according to the type of the variable (float or double), but I am not sure whether the following implementation is the right way to do it. Need some suggestions on it.

// computeFloat is a method of some other class which actually computes and returns a float value
float computeFloat()
{
   float a;
   .... 
   return a; 
}

// setFloat is a method of some other class which actually sets a float value
void setFloat(float val)
{
  .....
}

TestClass<T> : IDisposable
{

public void getValue(ref T val)
{
   if(val is float)
   {
      object retVal = computeFloat();
      val = (float)retVal;
   }
   else
   { 
       throw new Exception(" Not implemented");
   }
}

public void setValue(T val)
{
   if(val is float)
   {
      object obj = val as object;
      float retVal = (float)obj;

       setFloat(retVal);
   }
   else
   { 
       throw new Exception(" Not implemented");
   }

}   

}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
veda
  • 6,416
  • 15
  • 58
  • 78
  • Consider checking Mark Gravell's http://www.yoda.arachsys.com/csharp/miscutil/usage/genericoperators.html... (linked from http://stackoverflow.com/questions/32664/c-sharp-generic-constraint-for-only-integers) – Alexei Levenkov Oct 03 '13 at 00:15
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Oct 03 '13 at 00:17

1 Answers1

1

You can look into the following to avoid if statements. You can also consider adding filters on the class to limit it to certain types.

public void getValue(ref T val)
{
   object retVal = compute<T>();
   val = (T)retVal;
}
TGH
  • 38,769
  • 12
  • 102
  • 135