Artur Michajluk
Artur Michajluk

Reputation: 1967

Why default operator for int? is not consistent?

Why default is returning different values? Is it because of null coalescing operator?

Code (FYI .Dump() is from LinqPad):

void Main()
{
    Foo foo = null;
    int? a = default;
    a.Dump("a"); // returns null

    a = foo?.Bar ?? default;
    a.Dump("a"); // returns 0

    a = foo?.Bar ?? default(int?);
    a.Dump("a"); // returns null

    (foo?.Bar is null ? default : "ADsf").Dump();
}

class Foo
{
    public int? Bar { get; set; }
}

Upvotes: 0

Views: 213

Answers (1)

Rekkon
Rekkon

Reputation: 325

For the simple variable declaration statement here:

int? a = default;

default is always the default value of the type that the variable is assigned. Since you explicitly declared a to have a type of int?, default will be equal to default(int?).

Null-coalescing (??) of a nullable value type will attempt to return a non-null value type (your typical struct, in this case int).

Therefore in this example:

a = foo?.Bar ?? default;

default will be equal to default(int) as it attempts to return an int object through the operator.

And in this example:

a = foo?.Bar ?? default(int?);

since default(int?) returns an object of type int?, it will either enforce the left hand to be cast to int?, or int? be cast to int. Since int is implicitly cast to int?, the null coalescing operator will consider returning int? in this case.

Upvotes: 1

Related Questions