Boş bir cüzdan düşün. İçinde para yok — ama cüzdan var. Şimdi bir de cüzdanın hiç olmadığı durumu düşün. İşte null tam olarak budur: nesnenin kendisinin yokluğu.
Yazılımda bir değişken henüz hiçbir nesneye işaret etmiyorsa değeri null'dır.
Think of an empty wallet. There's no money inside — but the wallet exists. Now imagine there is no wallet at all. That is exactly what null is: the absence of the object itself.
In software, if a variable doesn't point to any object yet, its value is null.
Olmayan bir nesnenin metodunu çağırmaya çalışırsan program NullReferenceException fırlatır ve çöker. Bu yazılımda en sık karşılaşılan hatalardan biridir.
If you try to call a method on an object that doesn't exist, the program throws a NullReferenceException and crashes. This is one of the most common errors in software.
string isim = null;
Console.WriteLine(isim.Length); // PATLAMA: NullReferenceException
// isim null olduğu için .Length çağrılamaz
Değer tipleri (int, bool, DateTime) normalde null olamaz. Ama bazen bir sayının "henüz girilmemiş" olduğunu ifade etmek istersin. Bunun için ? kullanılır.
Value types (int, bool, DateTime) normally cannot be null. But sometimes you want to express that a number "hasn't been entered yet". For this you use ?.
int sayi = null; // HATA — int null olamaz
int? sayi = null; // DOĞRU — nullable int
string? isim = null; // C# 8+ ile string de nullable olabilir
if (sayi.HasValue)
Console.WriteLine(sayi.Value);
else
Console.WriteLine("Değer girilmemiş.");
?. (null-conditional) operatörü: nesne null ise patlamak yerine null döndürür.?? (null-coalescing) operatörü: sol taraf null ise sağ taraftaki varsayılan değeri kullanır.
?. (null-conditional): if the object is null, returns null instead of crashing.?? (null-coalescing): if the left side is null, uses the default value on the right.
string? isim = null;
// ?. operatörü — null ise patlamaz, null döner
int? uzunluk = isim?.Length; // null
// ?? operatörü — null ise varsayılanı kullan
string gosterim = isim ?? "Misafir";
Console.WriteLine(gosterim); // "Misafir"
// İkisini birlikte kullanmak
string sonuc = isim?.ToUpper() ?? "BİLİNMİYOR";
Console.WriteLine(sonuc); // "BİLİNMİYOR"