ToString() Override
Part of the Object Oriented Programming section of Coddy's C# journey — lesson 38 of 70.
Every class in C# inherits from object, which provides a ToString() method. By default, it returns the fully qualified type name - not very useful when you want to see an object's actual data.
You can override ToString() to return a meaningful string representation of your object:
public class Person
{
public string Name { get; }
public int Age { get; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
public override string ToString()
{
return $"{Name} ({Age} years old)";
}
}Now when you print or concatenate a Person object, you get readable output:
Person p = new Person("Alice", 30);
Console.WriteLine(p); // Alice (30 years old)Without the override, this would print something like MyNamespace.Person. The override keyword is required because you're replacing the inherited method from object. This is especially valuable for debugging and logging, where you need quick insight into an object's state.
Challenge
EasyLet's build a Book class that provides meaningful string representations when printed, making debugging and displaying book information much more intuitive.
You'll organize your code across two files:
Book.cs: Create aBookclass in theLibrarynamespace that represents a book with its essential details. Your book should have:- Three read-only properties:
Title(string),Author(string), andYear(int) - A constructor that accepts title, author, and year in that order
- An overridden
ToString()method that returns a formatted string:"{Title}" by {Author} ({Year})
- Three read-only properties:
Program.cs: In your main file, create aBookobject using input values and print it directly. Thanks to yourToString()override, passing the book object toConsole.WriteLine()will automatically display the formatted information instead of the type name.
You will receive three inputs:
- Book title (string)
- Author name (string)
- Publication year (integer)
Print the book object directly using Console.WriteLine().
For example, if the inputs are The Great Gatsby, F. Scott Fitzgerald, and 1925, the output should be:
"The Great Gatsby" by F. Scott Fitzgerald (1925)The magic here is that you're not calling ToString() explicitly - when you pass an object to Console.WriteLine(), it automatically calls the object's ToString() method. Your override makes this output useful instead of just showing Library.Book!
Cheat sheet
Every class in C# inherits from object, which provides a ToString() method. By default, it returns the fully qualified type name.
Override ToString() to return a meaningful string representation:
public class Person
{
public string Name { get; }
public int Age { get; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
public override string ToString()
{
return $"{Name} ({Age} years old)";
}
}When you print an object, ToString() is called automatically:
Person p = new Person("Alice", 30);
Console.WriteLine(p); // Alice (30 years old)The override keyword is required when replacing an inherited method from object.
Try it yourself
using System;
using Library;
class Program
{
public static void Main(string[] args)
{
// Read input
string title = Console.ReadLine();
string author = Console.ReadLine();
int year = Convert.ToInt32(Console.ReadLine());
// TODO: Create a Book object using the input values
// TODO: Print the book object directly using Console.WriteLine()
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesNamespaces & DirectivesIntro to Classes & ObjectsThe 'this' KeywordMethods and ParametersFields vs PropertiesConstructorsObject InitializersRecap - Simple Calculator4Inheritance
Basic Inheritance (:) SyntaxThe 'base' KeywordVirtual & Override KeywordsSealed ClassesThe 'object' Base ClassRecap - Employee Hierarchy7Advanced Features
Operator OverloadingIndexers (this[])ToString() OverrideExtension MethodsRecap - Custom List2Properties & Static Members
Auto-Implemented PropertiesRead/Write-Only PropertiesStatic Fields & MethodsStatic ClassesExpression-Bodied Members5Polymorphism & Interfaces
Compile vs Runtime PolyInterface vs Abstract ClassMultiple InterfacesExplicit InterfacesUpcasting & DowncastingRecap - Shape Calculator