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

2019-04-23 14:06发布

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

标签: c# .net symbols
5条回答
等我变得足够好
2楼-- · 2019-04-23 14:43

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楼-- · 2019-04-23 14:44

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!

查看更多
做个烂人
4楼-- · 2019-04-23 14:49

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);
查看更多
孤傲高冷的网名
5楼-- · 2019-04-23 14:52

it's an equivalent of

(str == null ? string.Empty : str)
查看更多
SAY GOODBYE
6楼-- · 2019-04-23 14:52
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;
查看更多
登录 后发表回答