#184 – Cheating Type Safety with object Type
December 18, 2010 1 Comment
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:
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 to object.
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.
string s = "Uh-oh"; sum = AddNums(s, 1);