Possible Duplicate:
What is the “??” operator for?
I saw a line of code which states -
return (str ?? string.Empty).Replace(txtFind.Text, txtReplace.Text);
I want to know the exact meaning of this line(i.e. the ??
part)..
Possible Duplicate:
What is the “??” operator for?
I saw a line of code which states -
return (str ?? string.Empty).Replace(txtFind.Text, txtReplace.Text);
I want to know the exact meaning of this line(i.e. the ??
part)..
It's called the null coalescing operator. It allows you conditionally select first non-null value from a chain:
The value in
result
will be either the value ofnickname
if it's not null, or"<default>"
.The ?? operator says that return me the non null value. So, if you have the following code:
The above code will return "John Doe" since firstName value is null.
That's it!
It's the null coalescing operator: it returns the first argument if it's non null, and the second argument otherwise. In your example,
str ?? string.Empty
is essentially being used to swap null strings for empty strings.It's particularly useful with nullable types, as it allows a default value to be specified:
Edit:
str ?? string.Empty
can be rewritten in terms of the conditional operator asstr != null ? str : string.Empty
. Without the conditional operator, you'd have to use a more verbose if statement, e.g.:it's an equivalent of
could be written as:
or as a ternary statement: