Coming from Basic boolean logic in C#, I was wondering why:
Dim b As Boolean
Dim obj As Object = Nothing
'followig evaluates to False'
b = DirectCast(Nothing, Boolean)
'This throws an "Object reference not set to an instance of an object"-Exception'
b = DirectCast(obj, Boolean)
A CType(obj, Boolean)
would evaluate to False
(just as CBool(obj))
. I think it is because the compiler uses a helper function, but that is not my theme.
Why does casting Nothing
to Boolean
evaluates to False
, whereas casting an object that is Nothing
to Boolean
throws an Nullreference-Exception? Does that make sense?
[Option Strict ON]
Presumably, this is because Nothing
in VB.NET is not exactly the same thing as null
in C#.
In the case of value types, Nothing
implies the default value of that type. In the case of a Boolean
, the default value is False
, so the cast succeeds.
One of the primary differences between value types such as Integer or structures and reference types such as Form or String is that reference types support a null value. That is to say, a reference type variable can contain the value Nothing, which means that the variable doesn't actually refer to a value. In contrast, a value type variable always contains a value. An Integer variable always contains a number, even if that number is zero. If you assign the value Nothing to a value type variable, the value type variable just gets assigned its default value (in the case of Integer, that default value is zero). There is no way in the current CLR to look at an Integer variable and determine whether it has never been assigned a value - the fact that it contains zero doesn't necessarily mean that it hasn't been assigned a value.
–The Truth about Nullable Types and VB...
EDIT: For further clarification, the reason the second example throws a NullReferenceException
at run-time is because the CLR is attempting to unbox the Object
(a reference type) to a Boolean
. This fails, of course, because the object was initialized with a null reference (setting it equal to Nothing
):
Dim obj As Object = Nothing
Remember that, as I explained above, the VB.NET keyword Nothing
still works the same way as null
in C# when it comes to reference types. That explains why you're getting a NullReferenceException
because the object you're attempting to cast is literally a null reference. It does not contain a value at all, and therefore cannot be unboxed to a Boolean
type.
You don't see the same behavior when you try to cast the keyword Nothing
to a Boolean, i.e.:
Dim b As Boolean = DirectCast(Nothing, Boolean)
because the keyword Nothing
(this time, in the case of value types) simply means "the default value of this type". In the case of a Boolean
, that's False
, so the cast is logical and straightforward.