Skip to main content

Generics

Reusability in C#:

C# lets you reuse code in two major ways:

  1. Inheritance
  2. Generics
Let’s look at each:

1. Inheritance:

  • Inheritance is an object-oriented concept.
  • You write a base class and then extend it to create more specific classes.
  • Example:
     class Animal 
     {
           public void Eat() { Console.WriteLine("Eating..."); }
     }

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

     // Reusing code via inheritance
    Dog d = new Dog();
    d.Eat(); // From Animal
    d.Bark(); // From Dog

✅ Pros: Useful when classes share common behavior.
❌ Cons: Less flexible when working with types (like intstring, etc.)

2. Generics:

  • Generics allow you to write code using placeholder types.
  • Instead of writing multiple versions of the same class or method for different types (e.g., intstring), you write one generic version.
  • Example:
     class Box<T> 
     {
        public T Value;
     }

    Box<int> intBox = new Box<int> { Value = 123 };
    Box<string> strBox = new Box<string> { Value = "Hello" };

Here, T is a placeholder type — it could be anything.

✅ Why Generics are Better in Some Cases?

1. Type Safety:
  • Generics know the type at compile-time.
  • You get intellisense and compile-time errors if you use the wrong type.
     Box<int> b = new Box<int>();
     b.Value = "Hello"; // ❌ Compile-time error

2. No Boxing/Unboxing:
  • Boxing happens when a value type (like int) is converted to an object (reference type).
  • Generics avoid this, so they’re more efficient.
     object x = 5; // boxing
     int y = (int)x; // unboxing
  • If you use List<object>, you’d box every value type.
  • With List<int>, there’s no boxing.

๐Ÿ“ฆ Real-Life Example: Storage Box


๐Ÿง  Imagine:

You are building a program to manage storage boxes.

Each box can store only one item, but it could be an item of any type — a book, a toy, a shirt, etc.

❌ Without Generics:

You might create different classes for each type:

class BookBox 
{
  public Book Item;
}

class ToyBox 
{
    public Toy Item;
}

That's a lot of repetitive code and not scalable!

✅ With Generics:

Use one generic class for all types of boxes:

class StorageBox<T> 
{
    public T Item { get; set; }
}

Now you can create boxes for any type:

StorageBox<string> bookBox = new StorageBox<string>();
bookBox.Item = "C# Programming Book";

StorageBox<int> numberBox = new StorageBox<int>();
numberBox.Item = 123;

StorageBox<DateTime> dateBox = new StorageBox<DateTime>();
dateBox.Item = DateTime.Now;

๐Ÿ” Benefits:

  • Type-safe: You can't accidentally put a DateTime in a StorageBox<string>.

  • Reusable: One class handles all types.

  • Clean code: No code duplication.

๐Ÿงพ Real Code Example:

using System;

class StorageBox<T>
{
    public T Item { get; set; }
}

class Program
{
    static void Main()
    {
        var fruitBox = new StorageBox<string> { Item = "Apple" };
        var numberBox = new StorageBox<int> { Item = 42 };

        Console.WriteLine($"Fruit: {fruitBox.Item}");
        Console.WriteLine($"Number: {numberBox.Item}");
    }
}

Output:

Fruit: Apple
Number: 42


Comments

Popular posts from this blog

datatable compute sum in c# | datatable compute() function

datatable compute sum in c# | datatable compute() function Hi Readers, Today I am going to explain you the use of compute() function of Data table using C#.NET .  Let's begin.. datatable column sum in c# datatable compute sum in c# | datatable compute() function Let's say that we have the following rows filled in the Data table with the columns ID,NAME,AGE and SALARY as shown in snapshot below:- employees detail in datatable In order to calculate the figures like total of salary, average of salary, maximum salary and minimum salary, we can use the compute() function of the Data table. The compute() function loops through each value of the column's cell and then perform the calculation. For the above data table's salary column, lets find the total, average, maximum and minimum of salary one by one using compute() function:- datatable compute sum in c# | datatable compute() function Calculate the total of sala...

Adding rows to Datatable using C#.NET

Adding rows to Datatable using C#.NET Hi Readers, Today I am going to explain you 2 ways that we can use to add rows to a Data table using C#.NET.  So lets begin: Add row in datatable in c# Adding rows to Datatable using C#.NET > Lets say, we have a data table with the columns ID, NAME, AGE AND SALARY and I want to add rows to this data table using C# coding . > First of all, add columns to data table using the following lines of code: DataTable dtEmployee = new DataTable("Employee"); dtEmployee.Columns.Add("ID", typeof(int)); dtEmployee.Columns.Add("NAME", typeof(String)); dtEmployee.Columns.Add("AGE", typeof(int)); dtEmployee.Columns.Add("SALARY", typeof(Decimal)); Add row in datatable in c# > Now if we want to add rows to the above data table at run time, we have the following 2 ways to do so: Adding rows to Datatable using C#.NET 1. Using DataRows :- In this, we create an o...