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)..
In computer programming, ?: is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. It is commonly referred to as the conditional operator, inline if (iif), or ternary if. An expression a ? b : c evaluates to b if the value of a is true, and otherwise to c .
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:
int? nullableInt = GetNullableInt();
int normalInt = nullableInt ?? 0;
Edit: str ?? string.Empty
can be rewritten in terms of the conditional operator as str != null ? str : string.Empty
. Without the conditional operator, you'd have to use a more verbose if statement, e.g.:
if (str == null)
{
str = string.Empty;
}
return str.Replace(txtFind.Text, txtReplace.Text);
It's called the null coalescing operator. It allows you conditionally select first non-null value from a chain:
string name = null;
string nickname = GetNickname(); // might return null
string result = name ?? nickname ?? "<default>";
The value in result
will be either the value of nickname
if it's not null, or "<default>"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With