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.
In Java, null is neither an Object nor a type. It is a special value that we can assign to any reference type variable.
You can assign NULL to any pointer without any cast.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With