I'm CaLendarW Blog

C# ?? null coalescing operator

by on Jul.23, 2009, under coding snippet

null coalescing operator – ?? 係用黎決定參數是否 null 既算式, 自 C# 2.0 開始支援, 作為 null 既使用簡化.

// .net framework 1.1 既寫法
if (obj.Currency != null)
    cbxCurrency.SelectedItem = obj.Currency;
else
    cbxCurrency.SelectedItem = DefaultCurrency;
// .net framework 2.0 既寫法
cbxCurrency.SelectedItem = obj.Currency ?? DefaultCurrency;

長度上係短左, 識既人會易睇左. 另一方面, 通常既用法會同 Nullable 一齊用, 但自己平時無乜用開 Nullable, 所以對此無乜 comment (知道有呢樣野, 但唔知咩情況用先叫做適合, 所以都未用過.

// nullable int
int? i = null;
int result = i ?? 5;
// Output: result == 5
:

Leave a Reply

You must be logged in to post a comment.

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!