Possible Duplicate:
What is the “??” operator for?
I saw a line of code which 开发者_StackOverflowstates -
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 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>"
.
it's an equivalent of
(str == null ? string.Empty : str)
The ?? operator says that return me the non null value. So, if you have the following code:
string firstName = null;
string personName = firstName ?? "John Doe";
The above code will return "John Doe" since firstName value is null.
That's it!
str ?? String.Empty
could be written as:
if (str == null) {
return String.Empty;
} else {
return str;
}
or as a ternary statement:
str == null ? str : String.Empty;
精彩评论