What does <??> symbol mean in C#.NET? [dupli

2019-04-23 14:29发布

问题:

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)..

回答1:

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);


回答2:

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>".



回答3:

it's an equivalent of

(str == null ? string.Empty : str)


回答4:

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!



回答5:

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;


标签: c# .net symbols