Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

symbols

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

like image 896
Bibhas Debnath Avatar asked Feb 18 '10 16:02

Bibhas Debnath


People also ask

What does '?' Mean in C?

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 .


2 Answers

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);
like image 141
Will Vousden Avatar answered Oct 11 '22 17:10

Will Vousden


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

like image 44
Igal Tabachnik Avatar answered Oct 11 '22 15:10

Igal Tabachnik