Home About Lessons Blog On The Mic Contact Projects
Lessons BASIC · C#

C# Basics — Generics

9 min read · Emre Ulutabak
1
What is a generic?

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.

2
Why use it?

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.

3
Generic method
csharp
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 <T> expression means 'type parameter'. You can use any name instead of T, but T is the most common convention.
4
Generic class

The List<T> and Dictionary<TKey, TValue> you already use are generic classes. You can write your own generic class too.

csharp
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
5
Golden rules
💡
Generic structures are type-safe. If you pass the wrong type, you get a compile error — not a runtime crash.
💡
List<T>, Dictionary<K,V>, IRepository<T> — all of these are generic. This pattern is everywhere you look.
💡
Think of generics as a template to avoid rewriting the same code.
MINI QUIZ
Which is correct about generic types?
Generic structures only work with int
The letter T is mandatory and cannot be changed
Generic structures preserve type safety and make code reusable
List<T> is not a generic structure