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

Answers


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


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.


Need Your Help

How can I optimize images uploaded using Paperclip & Rails?

ruby-on-rails paperclip

Does anyone know how to optimize image size through paperclip?

Running a Java Program in Grails

java grails

I've written some small programs that help me out parsing/analysing data.