The ‘object’ Base Class in .NET

What is the Object Base Class?

In .NET, all types, whether value types or reference types, implicitly inherit from the object base class. This means that every type in .NET is derived from the object class, which provides a set of basic methods that can be used by all types. The object class serves as the ultimate base class for all types in .NET, making it a fundamental part of the framework.

Key Methods of the Object Class

The object base class provides several key methods that can be overridden in derived classes. These methods include:

  • ToString(): Returns a string representation of the object.
  • Equals(object obj): Determines whether the specified object is equal to the current object.
  • GetHashCode(): Returns a hash code for the object, often used in hashing algorithms and data structures like hash tables.
  • GetType(): Gets the runtime type of the current instance.

Example: Using Methods from the Object Class

Here’s an example of how some methods from the object class can be used in a simple C# program:

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

    public override string ToString()
    {
        return $"Person: {Name}";
    }
}

Person person = new Person() { Name = "Alice" };
Console.WriteLine(person.ToString());  // Output: Person: Alice
Console.WriteLine(person.GetType());  // Output: Person
Console.WriteLine(person.GetHashCode());  // Output: [HashCode of the person object]
        

In this example, the Person class overrides the ToString() method to provide a custom string representation of a Person object.

Object Class and Polymorphism

The object class plays a key role in polymorphism, allowing objects of any type to be treated as an object. This is particularly useful in scenarios where you want to write generic code that can handle objects of any type.

Example: Object Type and Polymorphism

object obj = new Person() { Name = "Bob" };
Console.WriteLine(obj.ToString());  // Output: Person: Bob

obj = 123;
Console.WriteLine(obj.ToString());  // Output: 123
        

In this example, the variable obj is an instance of the object class and can hold references to objects of different types (e.g., Person and int). This demonstrates the power of polymorphism in .NET.

Key Points to Remember

  • All types in .NET, including custom classes and structs, inherit from the object base class.
  • The object class provides fundamental methods like ToString(), Equals(), and GetHashCode(), which can be overridden in derived types.
  • Polymorphism allows any type to be treated as an object, providing flexibility in handling objects of different types.