When you unbox a value type that has been put into an object
box, you must use the correct cast. The conversion from one numeric type to another is an extra cast that comes after the unboxing.
In your case, however, the second cast is really implicit, so you could simplify a little bit to:
if (result is int)
return (int)result;
else
return (float)result;
Why do you have boxed value types in the first place? If you don't know what type is boxed, to unbox you will normally have to check with is
the way you do.
Note, however, that with (IConvertible
) types like these built-in numeric types, you can also use the Convert
class, so:
return Convert.ToSingle(result);
It looks more pretty, but I don't think it's faster. It will probably do the same kind of type checking.
If the parser
gives only numeric types, and if for some reason you insist on boxing these value types, you might as well box them to IConvertible
, so that involves changing the return type like this:
private IConvertible parser(string expr) {...}
Then your code could go so:
IConvertible result = parser(expr); // it's some number boxed in an IConvertible reference type
return result.ToSingle(null); // instance method in IConvertible