C# Tutorial

C# String

C# Array

C# Flow Control

C# Class and Object

C# Inheritance

C# Interface

C# Collection

C# Generic

C# File I/O

C# Delegate and Event

C# Exception

C# Process and Thread

C# ADO.NET Database Operations

C# Inheritance

In this tutorial, we will explore inheritance in C#, a fundamental concept in object-oriented programming. Inheritance allows you to create a new class that inherits the members (properties, methods, and events) of an existing class. The new class is called the derived class, and the existing class is called the base class.

  • Basic Syntax

The basic syntax for inheritance in C# is as follows:

public class DerivedClass : BaseClass
{
    // Additional members for the derived class
}
  • Base Class

Let's start by creating a simple Animal base class with a property and a method:

public class Animal
{
    public string Name { get; set; }

    public void Speak()
    {
        Console.WriteLine($"{Name} makes a sound.");
    }
}
  • Derived Class

Now, we can create derived classes that inherit from the Animal base class, such as Dog and Cat:

public class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine($"{Name} barks.");
    }
}

public class Cat : Animal
{
    public void Meow()
    {
        Console.WriteLine($"{Name} meows.");
    }
}

In this example, both the Dog and Cat classes inherit from the Animal base class. This means they inherit the Name property and the Speak method from the Animal class.

  • Using Inheritance

With inheritance in place, we can create objects of the derived classes and use their inherited members:

Dog dog = new Dog { Name = "Buddy" };
dog.Speak(); // Output: "Buddy makes a sound."
dog.Bark();  // Output: "Buddy barks."

Cat cat = new Cat { Name = "Whiskers" };
cat.Speak(); // Output: "Whiskers makes a sound."
cat.Meow();  // Output: "Whiskers meows."
  • Overriding Methods

In some cases, you may want a derived class to provide a different implementation of a method inherited from the base class. To do this, you can use the override keyword in the derived class and the virtual keyword in the base class:

public class Animal
{
    public string Name { get; set; }

    public virtual void Speak()
    {
        Console.WriteLine($"{Name} makes a sound.");
    }
}

public class Dog : Animal
{
    public override void Speak()
    {
        Console.WriteLine($"{Name} barks.");
    }
}

public class Cat : Animal
{
    public override void Speak()
    {
        Console.WriteLine($"{Name} meows.");
    }
}

Now, when you call the Speak method on a Dog or Cat object, the overridden implementation in the derived class will be executed:

Dog dog = new Dog { Name = "Buddy" };
dog.Speak(); // Output: "Buddy barks."

Cat cat = new Cat { Name = "Whiskers" };
cat.Speak(); // Output: "Whiskers meows."

This tutorial demonstrates the basics of inheritance in C#. Inheritance allows you to create a new class that inherits the members of an existing class, promoting code reuse and modularity. You can also override methods in derived classes to provide different implementations of inherited methods.

  1. How to use inheritance in C#

    Inheritance in C# allows a class (derived class) to inherit properties and behaviors from another class (base class). Here's a basic example:

    using System;
    
    // Base class
    class Animal
    {
        public void Eat()
        {
            Console.WriteLine("Animal is eating");
        }
    }
    
    // Derived class inheriting from Animal
    class Dog : Animal
    {
        public void Bark()
        {
            Console.WriteLine("Dog is barking");
        }
    }
    
    class Program
    {
        static void Main()
        {
            Dog myDog = new Dog();
            myDog.Eat();  // Inherited from Animal
            myDog.Bark(); // Defined in Dog
    
            Console.ReadLine();
        }
    }
    
  2. C# base class and derived class

    In the example above, Animal is the base class, and Dog is the derived class. The Dog class inherits the Eat method from the Animal class.

  3. Inheriting constructors in C#

    Constructors are not inherited by default, but you can explicitly call the base class constructor using base():

    class Animal
    {
        public Animal(string species)
        {
            Console.WriteLine($"Animal of species {species} is created");
        }
    }
    
    class Dog : Animal
    {
        public Dog() : base("Canine")
        {
            Console.WriteLine("Dog is created");
        }
    }
    
  4. Method overriding in C# inheritance

    Method overriding allows a derived class to provide a specific implementation for a method defined in the base class. Example:

    class Animal
    {
        public virtual void MakeSound()
        {
            Console.WriteLine("Animal makes a sound");
        }
    }
    
    class Dog : Animal
    {
        public override void MakeSound()
        {
            Console.WriteLine("Dog barks");
        }
    }
    
  5. Access modifiers in C# inheritance

    Access modifiers control the visibility of members in a class. Inheritance allows the derived class to access public and protected members of the base class. Example:

    class Animal
    {
        protected void ProtectedMethod()
        {
            Console.WriteLine("Protected method");
        }
    }
    
    class Dog : Animal
    {
        public void AccessProtectedMethod()
        {
            ProtectedMethod(); // Accessing protected method from the base class
        }
    }
    
  6. C# abstract classes and inheritance

    Abstract classes cannot be instantiated and can contain abstract methods that must be implemented by derived classes. Example:

    abstract class Shape
    {
        public abstract void Draw();
    }
    
    class Circle : Shape
    {
        public override void Draw()
        {
            Console.WriteLine("Drawing a circle");
        }
    }
    
  7. C# sealed classes and preventing inheritance

    The sealed keyword prevents a class from being inherited. Example:

    sealed class FinalClass
    {
        // Class members
    }
    
  8. Multiple inheritance in C#

    C# does not support multiple inheritance of classes, but you can achieve it through interfaces. Example:

    interface IFirstInterface
    {
        void MethodA();
    }
    
    interface ISecondInterface
    {
        void MethodB();
    }
    
    class MyClass : IFirstInterface, ISecondInterface
    {
        public void MethodA() { /* Implementation */ }
        public void MethodB() { /* Implementation */ }
    }
    
  9. C# inheritance vs. composition

    Inheritance represents an "is-a" relationship, while composition represents a "has-a" relationship. Composition is often preferred for building flexible and modular systems.

  10. Inheriting interfaces in C#

    Interfaces define contracts that can be inherited by classes:

    interface IShape
    {
        void Draw();
    }
    
    class Circle : IShape
    {
        public void Draw()
        {
            Console.WriteLine("Drawing a circle");
        }
    }
    
  11. Polymorphism and inheritance in C#

    Polymorphism allows objects of different types to be treated as objects of a common base type or interface. In the example above, a Dog object can be treated as an Animal due to inheritance.

  12. C# inheritance and method hiding

    Method hiding occurs when a derived class introduces a new member with the same name as a member in the base class. Example:

    class Animal
    {
        public void MakeSound()
        {
            Console.WriteLine("Animal makes a sound");
        }
    }
    
    class Dog : Animal
    {
        public new void MakeSound()
        {
            Console.WriteLine("Dog barks");
        }
    }