Search code examples
c#.netcastingnullabledbnull

Cast a null into something?


I had this interesting discussion today with a colleague. We were debating two pieces of code in C#.

Code Snippet 1:

if(!reader.IsDBNull(2))
{
  long? variable1 = reader.GetInt64(2)
}

Code Snippet 2:

long variable1 = reader.IsDBNull(2) ? (long?) null : reader.GetInt64(2)

Question is: is it a good practice to cast null into a nullable long? Or would you rather use the traditional if statement to avoid casting null to nullable long.


Solution

  • The expressions (type?)null, default(type?) and new Nullable<type>() end up being compiled into the same opcodes:

            long? x = (long?)null;
            long? y = default(long?);
            long? z = new Nullable<long>();
    

    is turned into:

        IL_0001: ldloca.s x
        IL_0003: initobj valuetype [mscorlib]System.Nullable`1<int64>
        IL_0009: ldloca.s y
        IL_000b: initobj valuetype [mscorlib]System.Nullable`1<int64>
        IL_0011: ldloca.s z
        IL_0013: initobj valuetype [mscorlib]System.Nullable`1<int64>
    

    In other words, if you are working with nullable types, you are free to use whichever version you like best. Note however, that you should try to avoid arithmetics with nullable types. If you want to return a nullable value from a conditional expression, both possible results must be nullable if one of them can be null. Any other way could cause an exception in that case.