Mar 27, 2009

Nullable and ?? Operator

After reading the article, The C# ?? null coalescing operator (and using it with LINQ), I did a quick test like the following code. It seems the compiler does different thing for Nullabe type, and other reference type with ?? operator. In fact, ?? should not be called operator, it is shortcut for compiler instruction. It will be more effective to use "t1.GetValueOfDefault()" than "t1 ?? 0" . But latter seems more language built-in feature than API.

int? t1 = null;
int t2 = t1 ?? 0;
int t3 = (t1.HasValue ? t1.GetValueOrDefault() : 0);
int t4 = t1.GetValueOrDefault();

DateTime? d1 = null;
DateTime d2 = d1.GetValueOrDefault();


string s = null;
string s2 = s ?? "fred";

//reflector translate to the following
    int? t1 = null;
    int? d3 = t1;
    int t2 = d3.HasValue ? d3.GetValueOrDefault() : 0;
    int t3 = t1.HasValue ? t1.GetValueOrDefault() : 0;
    int t4 = t1.GetValueOrDefault();
    DateTime d2 = null.GetValueOrDefault();
    string s = null;
    string s2 = s ?? "fred";