Complete C# Tutorial

πŸš€ Introduction to Generics in C# – A Beginner-Friendly Guide

πŸ‘‹ Welcome to Generics in C#!

Hey there, fellow coder! πŸŽ‰ Have you ever written the same function for different data types? Annoying, right? Well, C# Generics solve that problem! They allow us to write flexible, reusable, and type-safe code.

Imagine having a single method that works for integers, strings, and even custom objects! That’s the magic of Generics.

Let’s dive in and make your code smarter! πŸš€

πŸ€” What are Generics?

Generics in C# allow us to write code that works with any data type. Instead of defining a function for every possible data type, we can write a single, reusable function using Generics.

Β 

Example Without Generics (Old Way)

				
					class PrintUtility {
    public void PrintInt(int value) {
        Console.WriteLine(value);
    }
    
    public void PrintString(string value) {
        Console.WriteLine(value);
    }
}
				
			

Here, we need two methods just to print an integer and a string. Imagine doing this for every data type. That’s a nightmare! 😱

Β 

Example With Generics (Smart Way)

				
					class PrintUtility {
    public void Print<T>(T value) {
        Console.WriteLine(value);
    }
}
				
			

Now, the Print<T> method works for any data type! No more writing duplicate code. Just call Print(100), Print("Hello"), or Print(3.14), and it works! 🎯

Β 

🎯 Why Do We Need Generics?

Generics make our life easier by:

➑️ Avoiding Code Duplication – Write once, use multiple times.
➑️ Ensuring Type Safety – Catch errors at compile-time, not runtime.
➑️ Improving Performance – No boxing/unboxing (for value types).
➑️ Making Code More Flexible – Works with any data type.

πŸ“ Generics Syntax in C#

Here’s the basic syntax of a generic class:

				
					class GenericClass<T> {
    public T Data { get; set; }
}
				
			
  • T is a placeholder for any type (like int, string, double, etc.).
  • You define T once and use it multiple times.

🌍 Real-World Example

Imagine a shopping cart where you add books, electronics, or clothes.
With Generics, the cart can store any type of item without extra code!

				
					class Cart<T> {
    private List<T> items = new List<T>();

    public void AddItem(T item) {
        items.Add(item);
    }

    public void ShowItems() {
        foreach (var item in items) {
            Console.WriteLine(item);
        }
    }
    
    static void Main() {
        // Cart for Books (string)
        Cart<string> bookCart = new Cart<string>();
        bookCart.AddItem("C# Programming");
        bookCart.AddItem("Design Patterns");
        
        Console.WriteLine("πŸ“š Book Cart:");
        bookCart.ShowItems();

        // Cart for Prices (int)
        Cart<int> priceCart = new Cart<int>();
        priceCart.AddItem(499);
        priceCart.AddItem(999);
        
        Console.WriteLine("πŸ’° Price Cart:");
        priceCart.ShowItems();
    }
}
				
			

βœ”οΈ class Cart<T> β†’ This is a Generic Class. The <T> means it can work with any data type (int, string, object, etc.).

βœ”οΈ private List<T> items = new List<T>(); β†’ Creates a list to store items of type T.

βœ”οΈ AddItem(T item) β†’ This method adds an item to the cart. The item can be of any type.

βœ”οΈ ShowItems() β†’ Loops through the list and prints all items in the cart.

Β 

Expected Output:
				
					πŸ“š Book Cart:
C# Programming
Design Patterns

πŸ’° Price Cart:
499
999
				
			

How This Works?

  1. We created two shopping carts – one for books (Cart<string>) and one for prices (Cart<int>).
  2. We used AddItem() to add books and prices.
  3. Finally, ShowItems() printed all the items in each cart.

Β 

Why Is This Useful?

  • The same class works for books (string) and prices (int) without extra code!
  • Saves time and avoids duplicate logic!
  • Can be extended to store any object (e.g., Cart<Product>, Cart<Customer>).

Β 

πŸ”₯ Key Takeaway

Instead of writing separate cart classes for different data types, Generics allow us to create one flexible class that works for everything! πŸš€

πŸ”š Conclusion

Generics make coding in C# easier, cleaner, and more powerful. They save time, reduce errors, and keep your code flexible and reusable.

Β 

πŸš€ Next What?

In the next chapter, we’ll explore Generic Classes and Methods to build even more powerful reusable components! Stay tuned! 😊

Leave a Comment

Share this Doc

Introduction to Generic

Or copy link