Start learning free

LESSON 609 OF 637 · OBJECT-ORIENTED PROGRAMMING

Printing Objects in C# in C#

Lesson

TL ; DR:

Override ToString to return a string. Then Console.WriteLine shows that string for the object.


class Cat {
    public string name;

    public Cat(string name) {
        this.name = name;
    }

    public override string ToString() {
        return "Cat named " + name;
    }
}

// Console.WriteLine(new Cat("Tom")) prints Cat named Tom


Full lesson:

Every C# class inherits a ToString method from object. C# calls it to turn an object into text. The inherited one only returns the class name:

Cat

That tells you nothing about the cat.

So override ToString, as you overrode methods before. Return the text that stands for the object.

C# calls it whenever the object becomes text. Console.WriteLine(tom) does that. So do "I have " + tom and $"I have {tom}".

ToString is public override, takes no parameters and returns a string. It must return the text, not print it.


Your task

The Dog class below has a name and an age. Override ToString in it.

It returns the name, then " is ", the age and " years old". The code in MainFunction prints two dogs.

Expected output:

Rex is 3 years old
Bella is 5 years old
STEP 1 OF 2
    Ctrl + Enter to check

    Printing Objects in C#

    Keep going with C#500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free