System.Object Class

The base class for all types in the Common Type System (CTS) and the .NET Framework class library. It is the ultimate ancestor of every type, including user-defined types.

Syntax

public class Object

Remarks

Every type in the .NET Framework, whether it is a value type or a reference type, is implicitly derived from the Object class. This means that every value in the .NET Framework can be treated as an Object.

The Object class provides the following core functionalities:

While you generally do not need to derive your types from Object directly (as this is done implicitly), you can override certain methods of the Object class, such as Equals, GetHashCode, and ToString, to customize the behavior of your types.

Members

The Object class defines several instance methods:

Instance Methods

Method Description
Equals(object obj) Determines whether the specified object is equal to the current object.
Equals(object objA, object objB) Determines whether two specified objects are equal.
GetHashCode() Serves as a hash function for the current type.
GetType() Gets the Type of the current instance.
ReferenceEquals(object objA, object objB) Determines whether the specified object references are the same instance.
ToString() Returns a string that represents the current object.

Examples

Overriding ToString()

By overriding the ToString() method, you can provide a more meaningful string representation for your custom objects.

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

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

// Usage:
Person person = new Person { Name = "Alice", Age = 30 };
Console.WriteLine(person.ToString()); // Output: Person: Alice, Age: 30

Overriding Equals() and GetHashCode()

To implement custom equality logic for your objects, you should override both Equals() and GetHashCode().

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }

    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
            return false;

        Point other = (Point)obj;
        return X == other.X && Y == other.Y;
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(X, Y);
    }
}

// Usage:
Point p1 = new Point { X = 10, Y = 20 };
Point p2 = new Point { X = 10, Y = 20 };
Point p3 = new Point { X = 30, Y = 40 };

Console.WriteLine(p1.Equals(p2)); // Output: True
Console.WriteLine(p1.Equals(p3)); // Output: False

See Also