bsoundra
bsoundra

Reputation: 970

Behavior of C# with Nullables

In C#

int? a1 = 0;
int? a2 = 100;
a1 = a1 | default(int?);
a2 = a2 | default(int?);
Both a1 and a2 turns out to be null. Would be great if someone would explain its working.

Update

The reason I brought up this insane example was the behavior when int? is replaced by bool? and the binding process.

bool? a1 = null;
bool? a2 = true;
a1 = a1 | default(bool?);
a2 = a2 | default(bool?);

This piece of code does not give a warning saying the result of the expression is always null. The inferred reason is 'I_dont_know'|int = 'I_dont_know' where as 'I_dont_know' | true = true

Correct me If I'm wrong

Upvotes: 1

Views: 137

Answers (2)

John Feminella
John Feminella

Reputation: 311426

First note that this isn't different from writing:

int? a1 = 0   | default(int?);
int? a2 = 100 | default(int?);

Which is equivalent to:

int? a1 = 0   | null;
int? a2 = 100 | null;

since the default keyword used on a reference type yields null. And since

<any integer> | null

always evaluates to null, you have:

int? a1 = null;
int? a2 = null;

which explains why both values are null.

Upvotes: 5

chkdsk
chkdsk

Reputation: 1195

This is because of the following reasons..

1] default(int?) will always return 'null'
2] null | <anything> returns 'null'

http://msdn.microsoft.com/en-us/library/xwth0h0d%28v=vs.80%29.aspx

Btw, visual studio should complain that your expressions always resolve to null. (a warning).

Upvotes: 10

Related Questions