404 Not Found

404 Not Found


nginx

Inheritance

What Is Inheritance

Inheritance is a core mechanism of object-oriented programming that allows one class to reuse the members of another class and extend it with new functionality. C# only supports single inheritance, meaning a class can have only one direct base class.

Inheritance Syntax

Use class DerivedClass : BaseClass to declare an inheritance relationship. The derived class automatically acquires all non-private members of the base class.

Example

CSHARP
class Animal
{
    public string Name { get; set; }
    public void Eat()
    {
        Console.WriteLine($"{Name} is eating.");
    }
}

class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine($"{Name}: Woof!");
    }
}

class Program
{
    static void Main()
    {
        Dog dog = new Dog { Name = "Buddy" };
        dog.Eat();
        dog.Bark();
    }
}
▶ Try it Yourself
TEXT
Buddy is eating.
Buddy: Woof!

The base Keyword

base is used to call the base class's constructors and member methods. In a constructor, pass arguments to the parent constructor via base(args); in a method, call the parent implementation via base.Method().

Example

CSHARP
class Person
{
    public string Name { get; }

    public Person(string name)
    {
        Name = name;
    }

    public virtual void Introduce()
    {
        Console.WriteLine($"I am {Name}.");
    }
}

class Student : Person
{
    public int Grade { get; }

    public Student(string name, int grade) : base(name)
    {
        Grade = grade;
    }

    public override void Introduce()
    {
        base.Introduce();
        Console.WriteLine($"I am in grade {Grade}.");
    }
}

class Program
{
    static void Main()
    {
        Student s = new Student("Alice", 3);
        s.Introduce();
    }
}
▶ Try it Yourself
TEXT
I am Alice.
I am in grade 3.

Method Overriding with virtual/override

The base class marks overridable methods with virtual, and the derived class provides a new implementation using override. This is the foundation of polymorphism.

Example

CSHARP
class Shape
{
    public virtual double Area()
    {
        return 0;
    }
}

class Circle : Shape
{
    public double Radius { get; set; }

    public Circle(double radius)
    {
        Radius = radius;
    }

    public override double Area()
    {
        return Math.PI * Radius * Radius;
    }
}

class Rectangle : Shape
{
    public double Width { get; set; }
    public double Height { get; set; }

    public Rectangle(double w, double h)
    {
        Width = w;
        Height = h;
    }

    public override double Area()
    {
        return Width * Height;
    }
}

class Program
{
    static void Main()
    {
        Shape[] shapes = { new Circle(2), new Rectangle(3, 4) };
        foreach (Shape s in shapes)
        {
            Console.WriteLine($"Area: {s.Area():F2}");
        }
    }
}
▶ Try it Yourself
TEXT
Area: 12.57
Area: 12.00

Method Hiding with new

If a derived class defines a method with the same name as one in the base class without using override, the compiler issues a warning. The new keyword explicitly hides the base class method, indicating that this is an independent method rather than an override.

Example

CSHARP
class Base
{
    public void Greet()
    {
        Console.WriteLine("Hello from Base");
    }
}

class Derived : Base
{
    public new void Greet()
    {
        Console.WriteLine("Hello from Derived");
    }
}

class Program
{
    static void Main()
    {
        Derived d = new Derived();
        d.Greet();

        Base b = d;
        b.Greet();
    }
}
▶ Try it Yourself
TEXT
Hello from Derived
Hello from Base
💡 Difference between new hiding and override overriding: when called through a base class reference, new executes the base class version, while override executes the derived class version.

sealed: Preventing Inheritance

Applying sealed to a class means it cannot be inherited; applying it to a method means the method cannot be further overridden.

Example

CSHARP
class Config
{
    public virtual void Load()
    {
        Console.WriteLine("Loading config...");
    }
}

class JsonConfig : Config
{
    public sealed override void Load()
    {
        Console.WriteLine("Loading JSON config...");
    }
}

sealed class FinalClass
{
    public void DoWork() { }
}

class Program
{
    static void Main()
    {
        JsonConfig cfg = new JsonConfig();
        cfg.Load();
    }
}
▶ Try it Yourself
TEXT
Loading JSON config...
⚠️ Once JsonConfig.Load is marked sealed, any class deriving from JsonConfig can no longer override Load. Once FinalClass is marked sealed, no class can inherit from it at all.

Constructor Chaining in Inheritance

When a derived class object is created, the base class constructor always executes before the derived class constructor. If the base class has no parameterless constructor, the derived class must explicitly call base(args).

Example

CSHARP
class Vehicle
{
    public string Type { get; }

    public Vehicle(string type)
    {
        Type = type;
        Console.WriteLine($"Vehicle({type}) constructed");
    }
}

class Car : Vehicle
{
    public string Brand { get; }

    public Car(string brand) : base("Car")
    {
        Brand = brand;
        Console.WriteLine($"Car({brand}) constructed");
    }
}

class Program
{
    static void Main()
    {
        Car car = new Car("Toyota");
    }
}
▶ Try it Yourself
TEXT
Vehicle(Car) constructed
Car(Toyota) constructed

The object Root Class

All types in C# inherit from System.Object (alias object). It provides foundational methods such as ToString(), Equals(), GetHashCode(), and GetType().

Example

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

    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }

    public override string ToString()
    {
        return $"({X}, {Y})";
    }

    public override bool Equals(object obj)
    {
        if (obj is Point other)
        {
            return X == other.X && Y == other.Y;
        }
        return false;
    }

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

class Program
{
    static void Main()
    {
        Point p1 = new Point(1, 2);
        Point p2 = new Point(1, 2);
        Console.WriteLine(p1.ToString());
        Console.WriteLine(p1.Equals(p2));
        Console.WriteLine(p1.GetType().Name);
    }
}
▶ Try it Yourself
TEXT
(1, 2)
True
Point

The is and as Operators

is performs a type check and returns a bool; as performs a safe type conversion, returning null on failure instead of throwing an exception.

Example

CSHARP
class Animal { }
class Cat : Animal
{
    public void Meow() { Console.WriteLine("Meow!"); }
}
class Dog : Animal
{
    public void Bark() { Console.WriteLine("Woof!"); }
}

class Program
{
    static void Main()
    {
        Animal a = new Cat();

        if (a is Cat)
        {
            Console.WriteLine("a is a Cat");
        }

        if (a is Dog)
        {
            Console.WriteLine("a is a Dog");
        }
        else
        {
            Console.WriteLine("a is not a Dog");
        }

        Cat c = a as Cat;
        if (c != null)
        {
            c.Meow();
        }

        Dog d = a as Dog;
        Console.WriteLine($"as Dog result is null: {d == null}");
    }
}
▶ Try it Yourself
TEXT
a is a Cat
a is not a Dog
Meow!
as Dog result is null: True
💡 C# 7+ supports is pattern matching: if (a is Cat cat) can check the type and declare a variable at the same time.

❓ FAQ

Q Does C# support multiple inheritance?
A No. A class can only have one direct base class, but it can implement multiple interfaces.
Q What happens if I write a method with the same name without using override?
A The compiler produces a warning. The method implicitly hides the base class method; it is recommended to add new to declare this explicitly.
Q Can the base keyword be used in static methods?
A No. Both base and this refer to an instance, and static methods have no instance context.
Q What is the practical significance of a sealed class?
A It prevents the class from being inherited, ensuring its implementation cannot be modified, and allows the JIT compiler to perform more optimizations.
Q What is the difference between is and as?
A is returns a bool for type checking; as attempts a conversion and returns the object or null. as cannot be used with value types.

📖 Summary

📝 Exercises

  1. Define an Employee base class (with Name and Salary properties), derive a Manager class (with an additional Level property), and use base in the Manager constructor to call the parent constructor.
  2. Define a virtual void Work() method in Employee, override it with override in Manager, and call base.Work() inside the overridden method.
  3. Create an Employee[] array containing both Employee and Manager objects, use the is operator to determine the type, and output different information accordingly.
  4. Override the ToString() method in Manager to return a string containing Name, Salary, and Level.
  5. Declare a sealed class PayCalculator, then try to write a class that inherits from it and observe the compilation error.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏