Think of a box. Sometimes you put apples in it, sometimes pens, sometimes books. The box itself doesn't change — only its contents do.
Generics work exactly like this. Instead of rewriting the same code for different types, you take the type as a parameter from outside.
Without generics, you'd need to write the same logic separately for int, string, and every other type. That's both repetition and risk of error.
Generic structures keep the code reusable while preserving type safety.
public T IlkElemaniGetir<T>(List<T> liste)
{
if (liste.Count == 0)
throw new InvalidOperationException("Liste boş.");
return liste[0];
}
// Kullanım:
var sayilar = new List<int> { 10, 20, 30 };
var isimler = new List<string> { "Ali", "Veli", "Ayşe" };
Console.WriteLine(IlkElemaniGetir(sayilar)); // 10
Console.WriteLine(IlkElemaniGetir(isimler)); // Ali
The List<T> and Dictionary<TKey, TValue> you already use are generic classes. You can write your own generic class too.
public class Kutu<T>
{
private T _icerik;
public void Koy(T nesne)
{
_icerik = nesne;
}
public T Al()
{
return _icerik;
}
}
// Kullanım:
var elmaliKutu = new Kutu<string>();
elmaliKutu.Koy("Elma");
Console.WriteLine(elmaliKutu.Al()); // Elma
var sayiKutu = new Kutu<int>();
sayiKutu.Koy(42);
Console.WriteLine(sayiKutu.Al()); // 42