[nem-en] Nullable types
Kamil Skalski
kamil.skalski at gmail.com
Sun Jan 8 11:11:29 CET 2006
Just like I thought, int? has quite much compiler level changes. First
of all, it is a struct, so simply it cannot be assigned null. Also,
when we take a look at following program:
///////////////////
class B {
static void Main () {
int? x = null;
if (x == null)
System.Console.WriteLine ("is null");
System.Console.WriteLine (x.ToString ());
int? y = 1;
}
}
/////////////////////////
Then
- yes, it will compile :)
- yes, it will print "is null"
- no, it will not crash with NullReferenceException, it will print an
empty string
- no, IL for this program have nothing to do with IL for any other
type instead of Nullable:
////////////////////////////
.locals init (valuetype [mscorlib]System.Nullable`1<int32> V_0,
valuetype [mscorlib]System.Nullable`1<int32> V_1,
bool V_2)
IL_0000: nop
IL_0001: ldloca.s V_0
IL_0003: initobj valuetype [mscorlib]System.Nullable`1<int32>
IL_0009: ldloca.s V_0
IL_000b: call instance bool valuetype
[mscorlib]System.Nullable`1<int32>::get_HasValue()
IL_0010: stloc.2
IL_0011: ldloc.2
IL_0012: brtrue.s IL_001f
IL_0014: ldstr "is null"
IL_0019: call void [mscorlib]System.Console::WriteLine(string)
IL_001e: nop
IL_001f: ldloca.s V_0
IL_0021: constrained. valuetype [mscorlib]System.Nullable`1<int32>
IL_0027: callvirt instance string [mscorlib]System.Object::ToString()
IL_002c: call void [mscorlib]System.Console::WriteLine(string)
IL_0031: nop
IL_0032: ldloca.s V_1
IL_0034: ldc.i4.1
IL_0035: call instance void valuetype
[mscorlib]System.Nullable`1<int32>::.ctor(!0)
///////////////
So there are at least several compiler supported changes:
- treat 'null : Nullable[T]' as Nullable[T]();
- treat '(x : Nullable [T]) == null' as x.HasValue
- treat 'def x : Nullable[int] = 1' as 'def x = Nullable (1);'
--
Kamil Skalski
http://nazgul.omega.pl
More information about the devel-en
mailing list