Jara M
Jara M

Reputation: 125

C# Addition between objects that are numbers

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.

Upvotes: 1

Views: 828

Answers (2)

Paulo
Paulo

Reputation: 617

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; 
}

Upvotes: -1

Jon Skeet
Jon Skeet

Reputation: 1500065

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.

Upvotes: 13

Related Questions