Throw nickname at something?

Today I had an interesting discussion with a colleague. We discussed two pieces of C # code.

Code Snippet 1:

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

Fragment Code 2:

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

The question is, is it good practice to feed null to nullable long? Or you would prefer to use the traditional if statement to avoid casting nullto zero length.

+5
source share
4 answers

Expressions (type?)null, default(type?)and new Nullable<type>()ultimately come down to the same operation codes:

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

turns 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>

, NULL, , . , , . , , . .

+15

(long?) null

default(long?) 

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

null ( ):

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

:

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

. , , .

: , :

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 are not using the ternary operator (without casting to NULL), and reading the values ​​from the reader looks more beautiful:

long? variable1 = reader.GetNullableInt64(2);
+1
source

Snippet 2 is in my case, since in the case nullyou get 0that is a completely valid value forlong

0
source

All Articles