C#

C# Fundamentals

19 lessons

Progress0%
1. Introduction to C#
1What is C#?
2. Variables and Data Types
1Data Types in C#
3. Control Flow
ConditionalsLoops
4. Methods
Defining MethodsOptional Parameters and Overloading
5. Object-Oriented Programming
Classes and PropertiesInheritanceInterfaces and Generics
6. LINQ and Async
LINQ Queriesasync/await
7. Exception Handling
try/catch/finally & Exception TypesCustom Exceptions & IDisposable
8. Delegates & Events
Delegates & LambdaEvents & Event Handlers
9. Records & Pattern Matching
Record TypesPattern Matching & Switch Expressions
10. File I/O & JSON
File & Stream OperationsJSON Serialization
All Tutorials
C#Object-Oriented Programming
Lesson 8 of 19 min
Chapter 5 · Lesson 2

Inheritance

Inheritance in C#

Syntax Use : to inherit from a base class:

csharp
class Dog : Animal { … }

base keyword

  • base(args) — calls the base class constructor.
  • base.Method() — calls the base class implementation of a method.

virtual and override A base class marks overridable methods with virtual. Subclasses use override to provide new implementations:

csharp
public virtual string Sound() => "...";
// In subclass:
public override string Sound() => "Woof";

sealed

  • sealed class — cannot be subclassed.
  • sealed override — prevents further overriding of a method.

Key points:

  • C# supports single class inheritance.
  • new (method hiding) is different from override — it hides rather than overrides, breaking polymorphism.
  • All C# classes implicitly extend System.Object.

Code Examples

virtual, override, basecsharp
using System;
class Animal {
    public string Name { get; }
    public Animal(string name) => Name = name;
    public virtual string Sound() => "...";
    public string Describe() => $"{Name} says {Sound()}";
}

class Dog : Animal {
    public string Breed { get; }
    public Dog(string name, string breed) : base(name) => Breed = breed;
    public override string Sound() => "Woof";
}

class Cat : Animal {
    public Cat(string name) : base(name) {}
    public override string Sound() => "Meow";
}

class Program {
    static void Main() {
        Animal[] pets = { new Dog("Rex", "Labrador"), new Cat("Whiskers") };
        foreach (var pet in pets)
            Console.WriteLine(pet.Describe());
    }
}

virtual/override enables runtime polymorphism. The correct Sound() is called based on the actual object type, not the variable type.

Quick Quiz

1. What is the difference between `new` and `override` on a method?

2. What does `sealed class` mean in C#?

Was this lesson helpful?

PreviousNext