C# Inheritance

Creating Derived Classes:

To create a derived class, you use the : symbol followed by the name of the base class.

The derived class inherits all the members (fields, properties, methods) of the base class and can define additional members or override existing ones.

                                                    
                                                    public class Animal
{
    public void Eat()
    {
        Console.WriteLine("Animal is eating.");
    }
}

public class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("Dog is barking.");
    }
}
                                                    
                                                

Example:

Below is example that Animal is the base class, and Dog is the derived class.

                                                    
                                                    public class Animal
{
    public void Eat()
    {
        Console.WriteLine("Animal is eating.");
    }
}

public class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("Dog is barking.");
    }
}
                                                    
                                                

Below example, the Eat, Move, and Run methods are accessible in the Dog class because they have public, protected, and internal access modifiers respectively.

                                                    
                                                    public class Animal
{
    public void Eat() {}       // public method
    private void Sleep() {}    // private method
    protected void Move() {}   // protected method
    internal void Run() {}     // internal method
}

public class Dog : Animal
{
    public void Play()
    {
        Eat();     // accessible (inherited from base class)
        Move();    // accessible (inherited from base class)
        Run();     // accessible (inherited from base class)
        // Sleep(); // not accessible (private)
    }
}