Click here to Skip to main content
15,922,427 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi,
i have create following programm with generic type delegate and has a return type of generic Tresult.but Calculator.division method won't run due to type conversion error.
plz suggest me solution
thanks in advance.


C#
public delegate Tresult MyDelegate<T, F, Tresult>(T number1, F number2);
   class Program
   {
       static void Main(string[] args)
       {
           MyDelegate<int, int, double> mydel = new MyDelegate<int, int, double>(new Calculator<int, int, double>().division);
          double a= mydel(5,7);
          Console.WriteLine(a);
          Console.ReadKey();
       }
   }

   public class Calculator<T, F, Tresult>
   {
       public Tresult division(T t, F f1)
       {
          if(typeof(Tresult)==typeof(double))
              return  Convert.ToDouble(t) * Convert.ToDouble(f1) as Tresult;
       }
   }


[edit]Code block moved, escaped HTML reverted, minor layout tidy up - OriginalGriff[/edit]
Posted
Updated 5-Feb-11 20:04pm
v2

1 solution

Yuck. But not strictly your fault it's yuck.

C#
return Convert.ToDouble(t) * Convert.ToDouble(f1) as Tresult;


You can't use as Tresult because Tresult could be any type, and it doesn't know if there is a conversion. You could constrain the types of Tresult to be compatible with T and / or F, but that also is a messy job.

C#
return (Tresult) (Convert.ToDouble(t) * Convert.ToDouble(f1));


You can't cast it because it tries to find a direct conversion from an unspecified type. Nasty.

C#
return (Tresult) (object) (Convert.ToDouble(t) * Convert.ToDouble(f1));


You can get it to compile by doing a double cast via object (since anything can be cast to an object, and everything is derived from object).

Will it work reliably in practice? Probably not. Best guess is run time exceptions because of the lack of conversions. It may work if you are really careful what types you use, but...

I would avoid having such flexible generic methods, if only because they are a real PITA to test fully.
 
Share this answer
 
Comments
Espen Harlinn 6-Feb-11 6:44am    
Good answer :)
Olivier Levrey 6-Feb-11 8:55am    
I completely agree. In my opinion, generics shouldn't be used to do math operations (I tried once and quickly understood it was not a good idea ha ha). They are usefull for storage purposes like lists, queues, or whatever, but definitely not for math.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900