Generics allow you to write flexible, type-safe code.
📦 What are Generics?
- Let you create classes/methods that work with any data type.
- Example:
List<T>
can hold any type (List<int>
,List<string>
, etc.).
🔧 Why Use Generics?
- No need to write the same code for different types.
- Prevent type errors at compile time.
📝 Example: Generic List
1
2
3
4
5
6
7
List<int> numbers = new List<int>();
numbers.Add(1);
numbers.Add(2);
List<string> words = new List<string>();
words.Add("hello");
words.Add("world");
🛠️ Creating Your Own Generic Method
1
2
3
4
5
6
7
8
void PrintTwice<T>(T item)
{
Console.WriteLine(item);
Console.WriteLine(item);
}
PrintTwice("Hello");
PrintTwice(123);
💡 Try It!
Write a method that returns the first element of any list.
1
2
3
4
T FirstItem<T>(List<T> list)
{
return list[0];
}
Next: Using generic collections like List, Dictionary, Queue, and Stack!