I have two objects that can be represented as an int, float, bool, or string. I need to perform an addition on these two objects with the results being the same thing c# would produce as a result. For instance 1+"Foo" would equal the string "1Foo", 2+2.5 would equal the float 5.5, and 3+3 would equal the int 6 . Currently I am using the code below but it seems like incredible overkill. Can anyone simplify or point me to some way to do this efficiently?
private object Combine(object o, object o1) {
float left = 0;
float right = 0;
bool isInt = false;
string l = null;
string r = null;
if (o is int) {
left = (int)o;
isInt = true;
}
else if (o is float) {
left = (float)o;
}
else if (o is bool) {
l = o.ToString();
}
else {
l = (string)o;
}
if (o1 is int) {
right = (int)o1;
}
else if (o is float) {
right = (float)o1;
isInt = false;
}
else if (o1 is bool) {
r = o1.ToString();
isInt = false;
}
else {
r = (string)o1;
isInt = false;
}
object rr;
if (l == null) {
if (r == null) {
rr = left + right;
}
else {
rr = left + r;
}
}
else {
if (r == null) {
rr = l + right;
}
else {
rr = l + r;
}
}
if (isInt) {
return Convert.ToInt32(rr);
}
return rr;
}