CodeBlanks Logo Icon CodeBlanks

The Object class

C# course · Intermediate · Lesson 17/116

Learn Object, the ancestor of all classes, and ToString, Equals, GetHashCode.

The Object root class

In C# every class implicitly inherits from object (System.Object). You do not write : object; the compiler adds it automatically. That is why every object has ToString, Equals and GetHashCode methods.

An object reference can hold any object: object o = new Book(); is valid. With boxing you can also assign value types to object: object box = 42;.

ToString override

The default ToString returns the class name, which is often useless. In your own class you override it to produce a meaningful string: public override string ToString() { return Name + " - " + Age; }.

Then Console.WriteLine(person) automatically calls ToString and gives useful output. This is the most frequently overridden method for debugging and logging. Always return a meaningful, short representation.

Exercise Override ToString in the Person class

Define a Person class with public string Name { get; set; } and public int Age { get; set; } properties. Then add a public override string ToString() method with return Name + " - " + Age; in the body. Inside Main create an instance with new Person { Name = "Alex", Age = 30 } and print it with Console.WriteLine(person).

Show example solution
Add Name and Age properties to Person. Write ToString override with return Name + " - " + Age;. In Main write Person p = new Person { Name = "Alex", Age = 30 }; Console.WriteLine(p);
Example solution:
using System;

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public override string ToString()
    {
        return Name + " - " + Age;
    }
}

class Program
{
    static void Main()
    {
        Person p = new Person { Name = "Alex", Age = 30 };
        Console.WriteLine(p);
    }
}

Test yourself

  1. Match each Object method to its purpose

    ToString
    Text representation
    Equals
    Equality check
    GetHashCode
    Hash code
    GetType
    Type info
  2. What class does every class inherit from?

    • object
    • string
    • System
    • void
    Show answer

    object — Correct. Every class inherits from object.

  3. Complete the ToString override

    public override string ____() { return Name; }
    Show answer
    public override string ToString() { return Name; }

All lessons in Intermediate