Inheritance is one of the core pillars of Object-Oriented Programming (OOP) in C#. It enables new classes to be based on existing classes, promoting code reuse, extensibility, and a clear hierarchical relationship between types. This detailed guide covers everything you need to know about inheritance in C#, from basic concepts to advanced usage, including examples and best practices.
Inheritance allows a class (called the derived class or child class) to inherit members (fields, properties, methods, events) from another class (called the base class or parent class). This relationship models an "is-a" association β the derived class is a specialized version of the base class.
Consider a base class Animal and derived classes like Dog and Cat. Dogs and cats share common animal properties (like breathing and eating) but also have specialized behaviors.
Inheritance is implemented using the colon (:) syntax after the derived class name.
public class Animal
{
public void Eat()
{
Console.WriteLine("Eating...");
}
}
public class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Barking...");
}
}
In this example, Dog inherits Eat() method from Animal, and also has its own Bark() method.
Dog myDog = new Dog();
myDog.Eat(); // Output: Eating...
myDog.Bark(); // Output: Barking...
C# supports several inheritance patterns:
One derived class inherits from one base class.
class Vehicle
{
public void Start() => Console.WriteLine("Vehicle started.");
}
class Car : Vehicle
{
public void Drive() => Console.WriteLine("Car is driving.");
}
A class derives from a derived class.
class Animal
{
public void Eat() => Console.WriteLine("Eating...");
}
class Mammal : Animal
{
public void Walk() => Console.WriteLine("Walking...");
}
class Dog : Mammal
{
public void Bark() => Console.WriteLine("Barking...");
}
Multiple classes inherit from a single base class.
class Animal
{
public void Eat() => Console.WriteLine("Eating...");
}
class Dog : Animal
{
public void Bark() => Console.WriteLine("Barking...");
}
class Cat : Animal
{
public void Meow() => Console.WriteLine("Meowing...");
}
C# does not support multiple class inheritance but allows multiple interface inheritance.
interface IWalkable
{
void Walk();
}
interface ISwimmable
{
void Swim();
}
class Amphibian : IWalkable, ISwimmable
{
public void Walk() => Console.WriteLine("Walking...");
public void Swim() => Console.WriteLine("Swimming...");
}
Access modifiers control visibility of class members in inheritance scenarios.
| Modifier | Access within Derived Class | Access Outside Assembly |
|---|---|---|
| public | Yes | Yes |
| private | No | No |
| protected | Yes | No |
| internal | Yes (if same assembly) | No |
| protected internal | Yes | Yes if same assembly |
protected members are accessible only within the class and its derived classes, which is key for inheritance encapsulation.
public class Animal
{
protected string name;
protected void SetName(string n)
{
name = n;
}
}
public class Dog : Animal
{
public void Initialize(string dogName)
{
SetName(dogName);
Console.WriteLine($"Dog's name is {name}");
}
}
Derived classes do not inherit constructors but can call base class constructors explicitly using the base keyword.
public class Person
{
public string Name;
public Person(string name)
{
Name = name;
}
}
public class Employee : Person
{
public int EmployeeId;
public Employee(string name, int id) : base(name)
{
EmployeeId = id;
}
}
When creating an object of a derived class:
Inheritance allows derived classes to modify behavior of base class methods via overriding.
Base class methods declared with virtual can be overridden.
public class Animal
{
public virtual void Speak()
{
Console.WriteLine("Animal speaks");
}
}
public class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("Dog barks");
}
}
You can call the base implementation from the override:
public override void Speak()
{
base.Speak();
Console.WriteLine("Dog barks");
}
With polymorphism, base class references can point to derived objects:
Animal myAnimal = new Dog();
myAnimal.Speak(); // Output: Dog barks
This decision is made at runtime (late binding), enabling dynamic behavior.
You can prevent further overriding using the sealed modifier:
public class Dog : Animal
{
public sealed override void Speak()
{
Console.WriteLine("Dog barks");
}
}
public class Puppy : Dog
{
// Compile error if trying to override Speak()
}
Derived classes can hide base class members using the new keyword instead of overriding.
public class BaseClass
{
public void Show()
{
Console.WriteLine("Base Show");
}
}
public class DerivedClass : BaseClass
{
public new void Show()
{
Console.WriteLine("Derived Show");
}
}
Unlike overriding, method hiding is resolved at compile time, based on reference type:
BaseClass obj1 = new DerivedClass();
obj1.Show(); // Output: Base Show
DerivedClass obj2 = new DerivedClass();
obj2.Show(); // Output: Derived Show
Abstract classes provide a base class with incomplete implementation and must be inherited.
public abstract class Shape
{
public abstract double GetArea(); // Abstract method without body
}
public class Circle : Shape
{
public double Radius;
public Circle(double radius)
{
Radius = radius;
}
public override double GetArea()
{
return Math.PI * Radius * Radius;
}
}
// Shape shape = new Shape(); // Compile error
While classes support single inheritance, C# allows a class to implement multiple interfaces, enabling a form of multiple inheritance.
public interface IPlayable
{
void Play();
}
public interface IRecordable
{
void Record();
}
public class MediaPlayer : IPlayable, IRecordable
{
public void Play() { Console.WriteLine("Playing media"); }
public void Record() { Console.WriteLine("Recording media"); }
}
public class Account
{
public string AccountNumber { get; set; }
public decimal Balance { get; protected set; }
public Account(string number, decimal initialBalance)
{
AccountNumber = number;
Balance = initialBalance;
}
public virtual void Deposit(decimal amount)
{
Balance += amount;
Console.WriteLine($"Deposited {amount}, new balance: {Balance}");
}
public virtual void Withdraw(decimal amount)
{
if (amount <= Balance)
{
Balance -= amount;
Console.WriteLine($"Withdrew {amount}, new balance: {Balance}");
}
else
{
Console.WriteLine("Insufficient funds");
}
}
}
public class SavingsAccount : Account
{
public double InterestRate { get; set; }
public SavingsAccount(string number, decimal balance, double interestRate)
: base(number, balance)
{
InterestRate = interestRate;
}
public void AddInterest()
{
decimal interest = Balance * (decimal)InterestRate / 100;
Deposit(interest);
Console.WriteLine($"Interest added: {interest}");
}
}
public class CheckingAccount : Account
{
public decimal OverdraftLimit { get; set; }
public CheckingAccount(string number, decimal balance, decimal overdraft)
: base(number, balance)
{
OverdraftLimit = overdraft;
}
public override void Withdraw(decimal amount)
{
if (amount <= Balance + OverdraftLimit)
{
Balance -= amount;
Console.WriteLine($"Withdrew {amount}, new balance: {Balance}");
}
else
{
Console.WriteLine("Exceeded overdraft limit");
}
}
}
Inheritance is a foundational concept in C# and OOP that facilitates reuse, organization, and polymorphism. It enables a derived class to inherit and modify behavior of a base class, promoting extensible and maintainable code.
Key points:
Mastering inheritance unlocks powerful design patterns and clean, scalable software architecture in C#.
C# is primarily used on the Windows .NET framework, although it can be applied to an open source platform. This highly versatile programming language is an object-oriented programming language (OOP) and comparably new to the game, yet a reliable crowd pleaser.
The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.
The decision to opt for C# or Node. js largely hinges on the specific requirements of your project. If you're developing a CPU-intensive, enterprise-level application where stability and comprehensive tooling are crucial, C# might be your best bet.
C# is part of .NET, a free and open source development platform for building apps that run on Windows, macOS, Linux, iOS, and Android. There's an active community answering questions, producing samples, writing tutorials, authoring books, and more.
Copyrights © 2024 letsupdateskills All rights reserved