What is the "??" operator for? [duplicate]
Asked Answered
A

12

35

I was wondering about ?? signs in C# code. What is it for? And how can I use it?

What about int?? Is it a nullable int?

See also:

?? Null Coalescing Operator —> What does coalescing mean?

Allocution answered 5/5, 2009 at 23:54 Comment(0)
A
35

It's called the "null coalescing operator" and works something like this:

Instead of doing:

int? number = null;
int result = number == null ? 0 : number;

You can now just do:

int result = number ?? 0;
Alkaloid answered 5/5, 2009 at 23:57 Comment(1)
Actually x ?? y calls x.GetValueOrDefault(y) (the IL code: call instance !0 valuetype [mscorlib]System.Nullable1<int32>::GetValueOrDefault()`)Rhizopod
N
53

It's the null coalescing operator. It was introduced in C# 2.

The result of the expression a ?? b is a if that's not null, or b otherwise. b isn't evaluated unless it's needed.

Two nice things:

  • The overall type of the expression is that of the second operand, which is important when you're using nullable value types:

    int? maybe = ...;
    int definitely = maybe ?? 10;
    

    (Note that you can't use a non-nullable value type as the first operand - it would be pointless.)

  • The associativity rules mean you can chain this really easily. For example:

    string address = shippingAddress ?? billingAddress ?? contactAddress;
    

That will use the first non-null value out of the shipping, billing or contact address.

Nerta answered 19/11, 2009 at 8:14 Comment(2)
it's equivalent to a!=null?a:bNunciata
@dharga: Except that it only evaluates a once.Nerta
A
35

It's called the "null coalescing operator" and works something like this:

Instead of doing:

int? number = null;
int result = number == null ? 0 : number;

You can now just do:

int result = number ?? 0;
Alkaloid answered 5/5, 2009 at 23:57 Comment(1)
Actually x ?? y calls x.GetValueOrDefault(y) (the IL code: call instance !0 valuetype [mscorlib]System.Nullable1<int32>::GetValueOrDefault()`)Rhizopod
S
12

That is the coalesce operator. It essentially is shorthand for the following

x ?? new Student();
x != null ? x : new Student();

MSDN Documentation on the operator

Strait answered 5/5, 2009 at 23:56 Comment(0)
I
8

It's the new Null Coalesce operator.

The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.

You can read about it here: http://msdn.microsoft.com/en-us/library/ms173224(VS.80).aspx

Into answered 5/5, 2009 at 23:57 Comment(0)
X
8

It is a shortcut for:

Text = (category == null ? "Home" : category);
Xena answered 19/11, 2009 at 8:13 Comment(0)
E
7

it's the coalesce operator. it will return another value if the first value is null

string value1 = null;
string value2 = "other";

string value3 = value1 ?? value2; // assigns "other" to value 3
Evita answered 5/5, 2009 at 23:56 Comment(0)
C
5

it checks if category is null - when this is the case the null value is replaced by "Home".

Carte answered 19/11, 2009 at 8:9 Comment(0)
D
4

One of my favorite uses for the null coalescing operator is to avoid if statements in my code (I think if statements are ugly and just clutter things up most times). For example, take a typical scenario where one might choose to load something from cache if available, otherwise load from the db and populate the cache.

private SomeData GetData() {
    var data = HttpRuntime.Cache.Get("key") as SomeData;

    if (data == null) {
        data = DAL.GetData(some parameters...);
        HttpRuntime.Cache.Add("key", data, ....);
    }

    return data;
}

To me, that's ugly code. I may be a bit anal, but why not refactor it to this instead?

private SomeData GetDataAndCache() {
    var data = DAL.GetData(some parameters...);
    HttpRuntime.Cache.Add("key", data, ....);
    return data;
}

private SomeData GetData() {
    var data = HttpRuntime.Cache.Get("key") as SomeData;
    return data ?? GetDataAndCache();
}

It more closely follows SRP and is cleaner and easier to read, IMO. The functions perform exactly one clearly identifiable function each.

Diverticulosis answered 6/5, 2009 at 0:25 Comment(5)
SRP: en.wikipedia.org/wiki/Single_responsibility_principleDiverticulosis
I wonder if the compiler renders it differently from an IF stament in the MSIL. Anyone know?Labor
doubt it, but i won't lose sleep over not knowing.Evita
I don't know that "if" statements are so ugly, but "assign only once" is a nice paradigm when you can do it without destroying the natural flow of the code.Ermentrude
Whether "if" statements are ugly is surely subjective, and I doubt my way improves performance. As I said, it just makes the code cleaner and easier to follow, IMO.Diverticulosis
G
4

if category is null, Text will become "Home"

Grus answered 19/11, 2009 at 8:9 Comment(0)
M
2

?? Null-Coalescing Operator

int? is a nullable int, which means it can have the values of a normal int and null. Read this for details.

Maziar answered 5/5, 2009 at 23:57 Comment(0)
T
2

Returns the first not-null value. Handy.

Thymic answered 5/5, 2009 at 23:57 Comment(0)
H
1

That's the null-coalescing operator . It's used with nullable types (among other things, sorry :)

Hagiographer answered 5/5, 2009 at 23:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.