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...

C# Dictionary

> In this post, we will see how to use a dictionary in C#. > A dictionary in C# is used to store collection of values with key values as pair. > So whenever user wants to get the value then he will have to pass the key value to the dictionary and it will return the value to the user. > The namespace of the C# dictionary is System.Collections.Generic. > Let’s take a simple example of storing digits from 0 to 9 as key value and these digits in the word form as the collection values. > Here, the user will type a digit from 0 to 9 and on clicking the button, it gives the digit in the word form. > To keep this example simple, here the dictionary will be having digits from 0 to 9 only and if user enters a value less than 0 or greater than 9 then he will get the appropriate message. > Following is the code for demonstrating the use of the Dictionary : HTML Code: <body>    <form id="form1" runat="server">   ...