The 'object' Base Class
Part of the Object Oriented Programming section of Coddy's C# journey — lesson 23 of 70.
In C#, every class you create automatically inherits from a special class called object. Even when you don't explicitly specify a base class, your class still has object as its ultimate ancestor. This means every type in C# shares a common set of methods.
The object class provides several virtual methods that you can override in your own classes:
public class Person
{
public string Name { get; set; }
// Override from object
public override string ToString()
{
return $"Person: {Name}";
}
public override bool Equals(object obj)
{
if (obj is Person other)
return Name == other.Name;
return false;
}
public override int GetHashCode()
{
return Name?.GetHashCode() ?? 0;
}
}The three most commonly overridden methods are ToString() for string representation, Equals() for comparing objects, and GetHashCode() for hash-based collections. By default, ToString() returns the type name, and Equals() checks reference equality.
Because everything inherits from object, you can store any type in an object variable:
object item1 = new Person { Name = "Alice" };
object item2 = 42;
object item3 = "Hello";
Console.WriteLine(item1.ToString()); // Person: AliceThis universal base class is what makes features like collections that hold mixed types possible, and it's why every object in C# has access to methods like ToString() and GetType().
Challenge
EasyLet's build a book comparison system that demonstrates how overriding methods from the object base class gives your custom types meaningful behavior for string representation and equality checking.
You'll create two files to organize your code:
Book.cs: Define aBookclass in theLibrarynamespace. Your book should haveTitle(string) andAuthor(string) properties, along with a constructor that sets both values. Override the three key methods inherited fromobject:ToString()should return"{Title} by {Author}"Equals(object obj)should returntrueif the other object is aBookwith the sameTitleandAuthorGetHashCode()should combine the hash codes of both properties
Program.cs: In your main file, create two books using input values. Display each book usingToString(), then check if they're equal and print the result. Finally, demonstrate that you can store aBookin anobjectvariable and still get meaningful output when callingToString().
You will receive four inputs:
- First book's title
- First book's author
- Second book's title
- Second book's author
Print the output in this format:
Book 1: {ToString result}
Book 2: {ToString result}
Are they equal? {True/False}
Stored as object: {ToString result of first book stored in object variable}For example, if the inputs are 1984, George Orwell, 1984, and George Orwell, the output should be:
Book 1: 1984 by George Orwell
Book 2: 1984 by George Orwell
Are they equal? True
Stored as object: 1984 by George OrwellIf the inputs are 1984, George Orwell, Brave New World, and Aldous Huxley, the output should be:
Book 1: 1984 by George Orwell
Book 2: Brave New World by Aldous Huxley
Are they equal? False
Stored as object: 1984 by George OrwellNotice how your overridden methods give Book objects meaningful behavior - they display nicely as strings and can be compared by their content rather than just their memory references!
Cheat sheet
In C#, every class automatically inherits from the object class, which provides several virtual methods that can be overridden:
Common Object Methods to Override
ToString()- Returns a string representation of the object (default returns the type name)Equals(object obj)- Compares objects for equality (default checks reference equality)GetHashCode()- Returns a hash code for use in hash-based collections
Overriding Object Methods
public class Person
{
public string Name { get; set; }
// Override ToString for custom string representation
public override string ToString()
{
return $"Person: {Name}";
}
// Override Equals for content-based comparison
public override bool Equals(object obj)
{
if (obj is Person other)
return Name == other.Name;
return false;
}
// Override GetHashCode for hash-based collections
public override int GetHashCode()
{
return Name?.GetHashCode() ?? 0;
}
}Universal Base Class
Any type can be stored in an object variable:
object item1 = new Person { Name = "Alice" };
object item2 = 42;
object item3 = "Hello";
Console.WriteLine(item1.ToString()); // Person: AliceThis universal inheritance enables collections that hold mixed types and ensures every object has access to methods like ToString() and GetType().
Try it yourself
using System;
using Library;
class Program
{
public static void Main(string[] args)
{
// Read input for two books
string title1 = Console.ReadLine();
string author1 = Console.ReadLine();
string title2 = Console.ReadLine();
string author2 = Console.ReadLine();
// TODO: Create two Book objects using the input values
// TODO: Print Book 1 using ToString()
// Format: "Book 1: {ToString result}"
// TODO: Print Book 2 using ToString()
// Format: "Book 2: {ToString result}"
// TODO: Check if the books are equal and print the result
// Format: "Are they equal? {True/False}"
// TODO: Store the first book in an object variable and print it
// Format: "Stored as object: {ToString result}"
}
}
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