Monday, June 22, 2026

C# Inheritance and generic compared - which one to use in program

Let us consider the following classes.
class Doctor
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;

    public void ShowInfo()
    {
        Console.WriteLine($"{Id} - {Name}");
    }
}

class Employee
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;

    public void ShowInfo()
    {
        Console.WriteLine($"{Id} - {Name}");
    }
}
Points to note
  • You find that Doctor and Employee classes are related because of common data/behavior.
  • This duplicates common logic in both classes.
  • In this case, Better solution → Inheritance (shared base class, Person)
  • Duplicate logic and data are placed in base class.
  • You can override logic in derived class.
class Person
{
    public int Id { get; set; }
    public string Name { get; set; }

    public void ShowInfo()
    {
        Console.WriteLine($"{Id} - {Name}");
    }
}
Create Derived classes
Now we can create classes which will inherit Id, Name, and ShowInfo() from Person.
class Doctor : Person { }
class Employee : Person { }
class Nurse : Person { }
class Teacher : Person { }

class Program
{
    static void Main(string[] args)
    {
        Doctor doctor = new Doctor { Id = 1, Name = "Dr. Smith" };
        Employee employee = new Employee { Id = 2, Name = "John Doe" };
        doctor.ShowInfo();
        employee.ShowInfo();
    }
}
👉Generics become useful when the logic stays same but type changes.
 
Example of generics:
class Repository<T>
{
    public void Save(T obj)
    {
        Console.WriteLine($"Saving {obj}");
    }
}
Usage:
Repository<Doctor> doctorRepo = new();
Repository<Employee> employeeRepo = new();
Repository<Teacher> teacherRepo = new();
Thus, only one repository class handles multiple types. So:
  • Inheritance → reuse common data/behavior among related classes
  • Generics → reuse same algorithm/business logic/data structure for different types

No comments:

Post a Comment

Hot Topics