C# Objects

Everything in C# is an Object.

Note

One exception to this generalization does exist. In an unsafe context, pointer types are not objects because they do not derive from System.Object.

Because everything is an Object, everything has four base methods:

  • Equals—Method to determine if two instances are equal

  • GetHashCode—Method to uniquely identify an Object

  • GetType—Method for obtaining the type of the Object

  • ToString—Method for converting the Object to a string

Would you expect the following to compile?

Console.WriteLine("{0}  {1} ", 1.ToString(), 1.GetType());

It not only compiles, but it also outputs this:

1 System.Int32

The following

Console.WriteLine("{0}  {1} ", 1.23.ToString(), 1.23.GetType());

outputs this

 1.23 System.Double  ...

Get .NET Common Language Runtime Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.