10 Temmuz 2016 Pazar

Null Coalescing Operator

Giriş
Açıklaması şöyle
The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.
Coalesce kelimesi co - alescere (Latince) kelimelerinden oluşuyor. Ben birleştirme diye çevirdim.

Coalesce (null birleştirme) bazı programlama dillerinde bulunan bir metod. Verilen bir çok parametreyi tek bir sonuç haline getiriyor. Yani birleştiriyor. Bunu yaparken null olmayan ilk değeri döndürüyor.

Getter İle Kullanım
Şöyle kullanırız..
get 
{ 
     _rows = _rows ?? new List<Row>(); 
     return _rows; 
}
Normal Kullanım
Şöyle yaparız:
MyName = s.MyName ?? string.Empty
Nullable İle Kullanım
Nullable tipler null coalescing operatörü ile beraber kullanılabilir.
Şöyle yaparız. x.BookingQuantity önce nullable integer'a döndürülüyor. Eğer döndürme sonucu null ise Sum 0 döner. Değilse BookingQuantity değerini döner.
var bookings = entities.Bookings.Where(x => x.ID == id)
                                .Sum(x => (int?)x.BookingQuantity) ?? 0;


Hiç yorum yok:

Yorum Gönder