#184 – 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:

        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);
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #184 – Cheating Type Safety with object Type

  1. Sean says:

    Really, we could say that we’re cheating “static typing” here, rather than cheating “type safety”.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: