Generics let you write methods and classes that work with any data type.
🛠️ Generic Method Example
1
2
3
4
5
6
T Echo<T>(T input)
{
return input;
}
Console.WriteLine(Echo(5)); // 5
Console.WriteLine(Echo("Hi")); // Hi
📦 Generic Class Example
1
2
3
4
5
6
7
8
class Box<T>
{
public T Value;
public Box(T value) { Value = value; }
}
Box<int> intBox = new Box<int>(10);
Box<string> strBox = new Box<string>("hello");
💡 Why Use Generics?
- No need to rewrite code for each type.
- Type safety: errors caught at compile time.
📝 Try It!
Write a generic method to swap two items:
1
2
3
4
5
6
void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
Next: Type safety with generics!