C# Generics

Serhat Selim
Sep 8, 2018 · 1 min read

Farklı tiplerde sayıları karşılaştırmak istediğimizi düşünelim ve elimizde de double ve int tipinde sayılar olsun,
her tipi kendi arasında karşılaştırmak için iki farklı metod yazmamız gerekir.

public int Max(int a, int b)
{
return a > b ? a : b;
}
public double Max(double a, double b)
{
return a > b ? a : b;
}

Bu kod tekrarını engellemek için generic yapısını kullanabiliriz ve tek bir metodla istediğimiz tipte sayı ikilisini karşılaştırabiliriz.

public class MyGenericClass<T> where T : IComparable
{
public T Max(T a, T b)
{

return a.CompareTo(b) > 0 ? a : b;

}

}


class Program
{
static void Main(string[] args)
{

var intNumber = new MyGenericClass<int>();
intNumber.Max(5, 6);

var doubleNumber = new MyGenericClass<double>();
doubleNumber.Max(5.5, 6.9);

}
}

Where

Generic class’ımıza kısıtlamalar koymak istersek “where” keywordunu kullanırız,

where T : struct   
// T referans parametremiz sadece int, float, double, DateTime, .. struct value tipinde olmak zorundadır
where T : class
// T referans parametremiz string yada custom bir referans tipinde olmak zorundadır
where T : new()
// T referans parametremiz default constructor'a sahip bir tipte olmalıdır aksi taktirde hata alırız
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade