Generics let us write code that works with any data type without repeating it. This saves time and avoids mistakes.
0
0
Why generics are needed in C Sharp (C#)
Introduction
When you want to create a list that can hold any type of item, like numbers or words.
When you write a method that should work with different data types but do the same job.
When you want to avoid writing the same code again for different types.
When you want your code to be safer by catching type errors early.
When you want to improve performance by avoiding extra type conversions.
Syntax
C Sharp (C#)
class ClassName<T> { // Use T as a placeholder for any type T data; void Method(T param) { // code using T } }
T is a placeholder for any type you choose when using the class or method.
You can use generics with classes, methods, interfaces, and more.
Examples
This class
Box can hold any type of value you give it.C Sharp (C#)
class Box<T> { public T Value; public Box(T value) { Value = value; } }
This method prints any type of item you pass to it.
C Sharp (C#)
void PrintItem<T>(T item) {
Console.WriteLine(item);
}Here we create two boxes: one for an integer and one for a string.
C Sharp (C#)
var intBox = new Box<int>(123); var strBox = new Box<string>("hello");
Sample Program
This program shows how one class Box can hold different types using generics. It prints the values stored.
C Sharp (C#)
using System; class Box<T> { public T Value; public Box(T value) { Value = value; } public void Show() { Console.WriteLine($"Value: {Value}"); } } class Program { static void Main() { var intBox = new Box<int>(100); var strBox = new Box<string>("Generics"); intBox.Show(); strBox.Show(); } }
OutputSuccess
Important Notes
Generics help avoid errors by checking types when you write code, not when it runs.
Without generics, you might use object type and need to convert types manually, which can cause mistakes.
Generics make your code cleaner and easier to understand.
Summary
Generics let you write flexible code that works with any data type.
They save time by avoiding repeated code for different types.
Generics improve safety by catching type errors early.