Jump to content

Null coalescing operator

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Grande (talk | contribs) at 19:58, 9 July 2007 (Page created. ~~~~). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

?? is an Operator (programming) that is part of the syntax for a basic conditional expression in several programming languages, specifically C#.

Conditional assignment

?: is most frequently used to simplify null expressions as follows:

possibly null value ?? value if null

The possibly null value is evaluated true or false as a Boolean expression. On the basis of the evaluation of the Boolean condition, the entire expression returns value if null if possibly null value is null, but possibly null value otherwise. This is similar to the way ternary operators (?: statements) work in functional programming languages.

This operator's most common usage is to minimize the amount of code used for a simple null check. (In this case, the expression is converted into a statement by appending a semicolon ; to the expression.) For example, if we wish to implement some C# code to give a page a default title if none is present, we may use the following statement:

string PageTitle = suppliedTitle ?? "Default Title";

instead of the more verbose

string PageTitle = suppliedTitle == null ? "Default Title" : suppliedTitle;

or even worse

string PageTitle;

if (suppliedTitle == null)
    PageTitle = "Default Title";
else
    PageTitle = suppliedTitle;

The three forms are equivalent.

See also