Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 895
Bull Avatar asked May 17 '12 10:05

Bull


People also ask

Can we assign null to an object?

In Java, null is neither an Object nor a type. It is a special value that we can assign to any reference type variable.

Can you cast null in C?

You can assign NULL to any pointer without any cast.

Can null be cast to int?

In other words, null can be cast to Integer without a problem, but a null integer object cannot be converted to a value of type int.

Can null be cast to Boolean?

Using the Boolean function The Boolean function is used to get the Boolean value (true or false) of any variable, condition, or object. To convert the null into Boolean we just need to pass the null in the Boolean function.


1 Answers

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.

like image 178
Wormbo Avatar answered Sep 20 '22 18:09

Wormbo