π 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 You Will Learn in This Lesson
βοΈ What are Generics? β The core idea behind generics.
βοΈ Why do we need Generics? β The problems they solve.
βοΈ Syntax and Usage β How to write generic classes and methods.
βοΈ Examples and Real-World Use Cases β Practical applications of generics.
βοΈ Code Demonstrations β Learn by doing with sample programs.
π€ 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 (likeint
,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?
- We created two shopping carts β one for books (
Cart<string>
) and one for prices (Cart<int>
). - We used
AddItem()
to add books and prices. - 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! π