Inheritance (C#)

Inheritance lets one class (the child) reuse and extend the members of another class (the parent) using a colon. The child gets the parent's fields, properties, and methods automatically.

C#

The child class can add new members or override existing ones. Mark a method virtual in the parent and override in the child to replace its behavior.

Use the base keyword to call the parent's version of a method or constructor. C# classes can inherit from only one base class, but can implement many interfaces.

Syntax

class Child : Parent { ... }

Examples

C#

class Animal
{
    public virtual string Speak() => "...";
}
class Cat : Animal
{
    public override string Speak() => "meow";
}

Console.WriteLine(new Cat().Speak());

Output:

meow

Learn it in a lesson

See also

Back to the Dictionary