C# Base

HTML
CSS
Bootstrap
JavaScript
C#
SQL
Salesforce Admin
Exercise
Study Material

Base Classes in C#

Inheritance Hierarchy:

A base class serves as the foundation for derived (child) classes, allowing the sharing of common functionality.

Derived classes inherit members (fields, methods, properties) from their base class.

// Base class

public class Vehicle

{

    public void Start()

    {

        Console.WriteLine(“Engine starting…”);

    }

 

    public void Stop()

    {

        Console.WriteLine(“Engine stopping…”);

    }

}

 

// Derived class inheriting from Vehicle

public class Car : Vehicle

{

    // Additional members specific to Car

}

Using the base Keyword:

The base keyword allows you to call members from the base class within a derived class.

public class FlyingVehicle : Vehicle

{

    public void Fly()

    {

        base.Start(); // Calling the Start method from the base class

        Console.WriteLine(“Taking off…”);

    }

}

Creating Instances:

You can create instances of derived classes and access both base and derived class members.

Car myCar = new Car();

myCar.Start(); // Calls the Start method from the base class

myCar.Stop();  // Calls the Stop method from the base class

Extending Functionality:

Derived classes can extend or override the functionality of the base class.

{

    // Override the Start method to provide electric car-specific behavior

    public override void Start()

    {

        Console.WriteLine(“Initializing electric motor…”);

        base.Start(); // Call the Start method from the base class

    }

}