Inheritance Basics
Inheritance lets a new class receive everything an older class has, like a child inheriting eye color. The new class can then add its own extras.
In this page:
Syntax
class BaseClass
{
public void MethodName() { }
}
class DerivedClass : BaseClass
{
// inherits MethodName and adds its own members
}
Inheritance Basics
Inheritance lets a class (the derived class) reuse and extend the fields and methods of another class (the base class) using the : syntax. The derived class automatically gets everything public and protected from its base.
This models "is-a" relationships, like a Dog being an Animal.
Note:
C# only supports single inheritance for classes — a class can inherit from just one base class.
Example: Inheritance Basics
using System;
class Animal
{
public string Name;
public void Eat()
{
Console.WriteLine($"{Name} is eating");
}
}
class Dog : Animal
{
public void Bark()
{
Console.WriteLine($"{Name} says Woof!");
}
}
class Program
{
static void Main(string[] args)
{
Dog d = new Dog { Name = "Rex" };
d.Eat();
d.Bark();
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Inheriting from a
sealedclass, which is a compile error. - Trying to inherit from more than one class, since C# supports single class inheritance.
- Using inheritance for unrelated classes instead of an is-a relationship.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: