CodeBlanks Logo Icon CodeBlanks

The Object class

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.

Practice 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).

Starter code

Program.cs
using System;

// Define Person class and add ToString override

class Program
{
    static void Main()
    {
        // Create a Person and print with WriteLine
    }
}

Sample solution

Program.cs
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);
    }
}

Expected output

Alex - 30

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each Object method to its purpose

Term Meaning
ToString Text representation
Equals Equality check
GetHashCode Hash code
GetType Type info

2 What class does every class inherit from?

  • string
  • object Correct answer
  • System
  • void

Explanation: Every class inherits from object.

3 Complete the ToString override

Question
public override string ____() { return Name; }
Answer
public override string ToString() { return Name; }

Explanation: ToString override gives the object's text representation.

All lessons in Intermediate