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

#34 – The object Type

In the .NET Framework, all types are derived from System.Object.  In C#, the object keyword is a synonym for this same type.  System.Object is the base class for all other types in .NET, including built-in types and custom types.

In C#, all types can be upcast to object.

 string msg = "A string";
 int n = 42;
 Person me = new Person("Sean", 46);

 // Can assign anything to an object variable
 object o = msg;
 o = n;
 o = me;

Any class that you create in C# is automatically derived from object.

The object type defines the following instance methods:

  • bool Equals(object)
  • void Finalize()
  • int GetHashCode()
  • Type GetType()
  • object MemberwiseClone()
  • string ToString()

The object type defines the following static methods:

  • bool Equals(object, object)
  • bool ReferenceEquals(object, object)

This means that every new class automatically inherits these methods.

 Person me = new Person("Sean", 46);
 int hash = me.GetHashCode();