-3
public class Calculate
{
    public static T Add<T>(T a, T b) where T : struct
    {
        return (T)((object)(Convert.ToDouble(a) + Convert.ToDouble(b)));
    }
}

run Calculate.Add(10, 20) will get error,why?

  • 5
    What is the error? – Steve Apr 03 '17 at 06:49
  • Explain the problem. – AsthaUndefined Apr 03 '17 at 06:52
  • 1
    You've ensured that the result of the addition is of type `double`. You then box that and try to unbox it as an `int`. Outside of some special options for enums, you can't unbox to a different datatype to what was boxed. – Damien_The_Unbeliever Apr 03 '17 at 06:56
  • Not sure why you are converting to double and then casting to double, as this is causing boxing and unboxng. When calling method just do 10d, 20d or whatever type of calculation you want. In the method just use a+ b; – Avneesh Apr 03 '17 at 06:57
  • See [invalid cast exception on int to double](http://stackoverflow.com/q/12647068/6400526) and [Why do I get InvalidCastException when casting a double to decimal](http://stackoverflow.com/questions/1667169/why-do-i-get-invalidcastexception-when-casting-a-double-to-decimal) – Gilad Green Apr 03 '17 at 06:57
  • When returning, he is casting object to "T" and its throwing InvalidCast exception. – Parag Apr 03 '17 at 06:57
  • @PeterDuniho - its a runtime error since the `Convert` class exposes overloads that take `object`s. – Damien_The_Unbeliever Apr 03 '17 at 06:58
  • @Damien_The_Unbeliever: yeah, I realized that as soon as I hit Enter – Peter Duniho Apr 03 '17 at 06:59
  • Please explain the problem more so you could get an answer. – Everyone Apr 03 '17 at 07:33

1 Answers1

0

Use this.

 return (T)Convert.ChangeType(Convert.ToDouble(a) + Convert.ToDouble(b), typeof(T));

It will convert your result to type "T".

Parag
  • 543
  • 1
  • 8
  • 18