Cast a null into something?

17,904

Solution 1

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.

Solution 2

Instead of

(long?) null

use

default(long?) 

I would refactor above code like

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

Solution 3

I prefer not to cast null value (it looks odd to me):

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

Another options:

long? variable1 = reader.IsDBNull(2) ? default : reader.GetInt64(2); // requires C# 7.1
long? variable1 = reader.IsDBNull(2) ? default(long?) : reader.GetInt64(2);
long? variable1 = reader.IsDBNull(2) ? (long?)null : reader.GetInt64(2);
long? variable1 = reader.IsDBNull(2) ? new Nullable<long>() : reader.GetInt64(2);
long? variable1 = reader.IsDBNull(2) ? new long?() : reader.GetInt64(2);
long? variable1 = reader.IsDBNull(2) ? null : new long?(reader.GetInt64(2));

It's just the matter of taste. I think first option is more readable, than others.

UPDATE: Consider also writing some extension methods to make your code more clear:

public static class DataReaderExtensions
{
    public static long? GetNullableInt64(this IDataReader reader, int index)
    {
        if (reader.IsDBNull(index))
            return null;

        return reader.GetInt64(index);
    }
}

In this case you don't use ternary operator (no casting to nullable), and reading values from reader looks more pretty:

long? variable1 = reader.GetNullableInt64(2);
Share:
17,904
Bull
Author by

Bull

Updated on June 04, 2022

Comments

  • Bull
    Bull almost 2 years

    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.