Cheating Type Safety with object Type

Since every object in C# derives from System.Object, it’s possible to “cheat” type safety by using the object type and casting objects to the desired type at run-time.
For example, assume we have a method that adds two parameters that are assumed to be numbers:
1
2
3
4
5
6
7
public static double AddNums(object n1, object n2)
{
    double d1 = Convert.ToDouble(n1);
    double d2 = Convert.ToDouble(n2);
 
    return d1 + d2;
}
This is convenient because now we can pass in any numeric type we like because we can implicitly cast anything toobject.
1
2
3
4
5
6
7
int i1 = 5, i2 = 7;
double d1 = 10.2, d2 = 23.2;
 
// These all work as expected
double sum = AddNums(i1, i2);
sum = AddNums(d1, d2);
sum = AddNums(i1, d1);
The problem is that the compiler won’t complain if we try to pass in some non-numeric object.  The following code will compile fine, but throw an exception at run-time.


1
2
string s = "Uh-oh";
sum = AddNums(s, 1);