Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is "?? "operator in c#? [duplicate]

Tags:

c#

Possible Duplicate:
What is the “??” operator for?

What does the "??" operator perform in an expression ?

public NameValueCollection Metadata
{
    get { return metadata ?? (metadata = new NameValueCollection()); }
}
like image 258
Emily Avatar asked Aug 07 '10 16:08

Emily


People also ask

What is operator and its example?

In mathematics and computer programming, an operator is a character that represents a specific mathematical or logical action or process. For instance, "x" is an arithmetic operator that indicates multiplication, while "&&" is a logical operator representing the logical AND function in programming.

What is operator and operand in C?

An operand can be a constant, a variable or a function result. Operators are arithmetic, logical, and relational. As with C, some operators vary in functionality according to the data type of the operands specified in the expression.


1 Answers

This is known as null-coalescing operator and it acts as following, assume a is a nullable int and b is a normal int

b = a ?? 1;

is equal to

b = (a != null ? (int)a : 1);

which is equal to

if(a != null)
    b = (int)a;
else
    b = 1;

Therefore

public NameValueCollection Metadata
{
    get { return metadata ?? (metadata = new NameValueCollection()); }
}

expanded should look like something like this

public NameValueCollection Metadata
{
    get
    {
        if(metadata == null)
            return (metadata = new NameValueCollection());
        else
            return metadata;
    }
}

which is some kind of a one liner singleton pattern, because the getter returns metadata (an initialized NameValueCollection object) every time its requested, expect the very first time which it's null at that point, so it initializes it and then returns it. This is off topic but note that this approach to singleton pattern is not thread-safe.

like image 114
Hamid Nazari Avatar answered Sep 30 '22 00:09

Hamid Nazari