1

I'm trying to find the best way to do following:

I have two Objects, object A and B. At some point in the program I know A and B are of type int, double or float. I would like to make an addition to them so A + B = C. C will be typed as we're used to while making addition between ints, floats, and doubles.

For example, if A was int and B float. Then C would be float.

Jara M
  • 125
  • 7
  • You're asking for the *compile-time* type of C to depend on the *run-time* types of A and B? –  May 14 '18 at 12:45
  • 2
    maybe generic types can help. Can you show us what you have tried please? – CodeNotFound May 14 '18 at 12:45
  • Generics can't help, as you would need to constrain the types as `must have operator +`, [which can't be done in C#](https://stackoverflow.com/questions/3598341/define-a-generic-that-implements-the-operator) – StuartLC May 14 '18 at 12:48
  • 1
    You should not be fighting against Strong Typisation. It is a important feature of .NET. Without it, we end up in the same problems as PHP or JavaScript programmres have: http://www.sandraandwoo.com/2015/12/24/0747-melodys-guide-to-programming-languages/ Do not fight it, embrace it. It is one of your strongest allies against bugs. Something with your whole design seems faulty if you can not even know the type of a variable. You should either pick one, or let teh user select one. – Christopher May 14 '18 at 12:55
  • 1
    This question is indicative of a design flaw. I think you should re-think your design. You should never have to force a square peg into a round hole like you're doing. – rory.ap May 22 '18 at 20:20

2 Answers2

13

The closest you can come is:

dynamic a = ...;
dynamic b = ...;
dynamic c = a + b;

That will perform the appropriate kind of addition, but you won't know the type of the result until execution time.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 2
    It should also be noted that it utterly breaks types. A function is handed a dynamic, is prone to return a dynamic as well - regardless wich types were specificed. Think of it as the Dark Side: "If once you go this path, forever will it dominate your destiny". – Christopher May 14 '18 at 13:04
  • I actually want to return Object. I know I could make a big switch on types of these methods and I could do all 27 cases how can I make an addition to three number objects. But that feels rather unclever. – Jara M May 14 '18 at 13:27
-1

I dont know if i understood your question, but I think this can help:

Object objectA, objectB, objectC; 
float objectFloatC;
// Your business logic here 

if((objectA is int) && (objectB is float))
{
   objectFloatC = (float)ObjectC; 
}
Paulo
  • 577
  • 3
  • 8
  • 23