VB.NET Nothing evaluating to False [duplicate] - vb.net

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.

There's a couple of things you have to realize here.
The first is what others have already pointed out: Nothing can be interpreted by the VB compiler as simply the Boolean value False given the proper context, such as Dim b As Boolean = Nothing.
This means that when the compiler sees this:
b = DirectCast(Nothing, Boolean)
It sees a literal (Nothing) and also sees that you want to use this literal as a Boolean. That makes it a no-brainer.
But now here's the second thing you have to realize. DirectCast on an Object is essentially an unboxing operation (for value types). So what needs to happen from the VB compiler's perspective is: there needs to be a Boolean in that box, or else the operation will fail. Since there is in fact nothing in the box—and this time we're really talking nothing, as in null—it throws an exception.
If I were to translate this code to C#, it would look like this:
bool b;
object obj = null;
b = (bool)default(bool);
b = (bool)obj;
Hopefully that makes things a bit clearer?

There's a difference between using the keyword (literal) Nothing, and using a reference variable whose value is Nothing.
In VB.NET, the literal (keyword) Nothing gets special treatment. The Nothing keyword can be automatically converted into a value type, using the default value of that type.
A reference variable whose value is Nothing is different. You don't get the special behaviour.
The documentation says DirectCast "requires an inheritance or implementation relationship between the data types of the two arguments".
Clearly Object does not inherit from or implement Boolean, unless you have put a boxed Boolean into an object variable.
So the code below fails at runtime with an exception.
Dim obj As Object = Nothing
b = DirectCast(obj, Boolean)

To get the expected behavior, you need this code:
Dim b As Boolean?
Dim obj As Object = Nothing
b = DirectCast(obj, Boolean?)
The character ? mean Nullable(of ).

I'm finding that comparing of the Boolean variable to a string of "True", "False" or Is nothing seems to ensure that I get the correct comparisons. I was using a function to return an html string of a div with an image of a checked or unchecked radio button and was having the issue of nothing coming back as false. Using the variable = "True" or "False" string and doing the last check with IS NOTHING helped to resolve that issue.
Dim b as boolean = nothing
response.write CheckValue(b = "True")
response.write (b = "False")
response.write (b is nothing)
Function CheckValue(inVal as boolean) as string
if inVal then
return ("<div><img src="checked.png" ></div>
else
return ("<div><img src="unchecked.png" ></div>
end if
end function
The system seems to do the conversion to string when implicitly compared to a string whereas using the .tostring method just creates an error while allowing the last comparison to actually compare to a value of nothing.
Hopefully that helps somewhat. It at least let me

Related

How to get CType/DirectCast working with a defined variable instead of a direct type?

I can't get the code below working.
The error is in the last line: Type 'ChangeType' is not defined.
Does the compiler thinks that ChangeType is a customtype which i did't have defiened ?
I have no clue, plz give me a hint.
May be I can't see the forest for the trees.
Dim DataValue as String = "True"
Dim ChangeTypeIndex() As String = {"System.Boolean", "System.Char", "System.SByte", "System.Byte", "System.Int16"}
Dim ChangeType As Type = Type.GetType(ChangeTypeIndex(0))
Dim Result = DirectCast(DataValue, ChangeType)
This is not possible in VB.NET. VB.NET is a type-safe language, and the express purpose of DirectCast is to aid in the compile-time type checking. Since it is analyzed for correctness at compile-time, it, by definition, can't be given a variable for the type. DirectCast can only be used to cast an object to another directly-related type (by inheritance or implementation). Since DataValue is a String, you couldn't cast it to a Boolean anyway (since String doesn't inherit from Boolean), even if DirectCast did allow you to pass a variable type like that.
.NET does support reflection and late-binding, so it is possible to do the same kind of thing, if you really need to, but it's generally a good idea to avoid these kinds of things as much as you can, so as to ensure that you are getting the most benefit out of the compiler's type-checking safety measures.
Warnings aside, if you really need to do this, a close approximation would be something like this:
Option Strict Off
' ...
Dim dataValue As String = "True"
Dim changeTypeIndex() As String = {"System.Boolean", "System.Char", "System.SByte", "System.Byte", "System.Int16"}
Dim changeType As Type = Type.GetType(changeTypeIndex(0))
Dim o As Object = Activator.CreateInstance(changeType)
Dim result As Object = o.Parse(dataValue)
Console.WriteLine(result.GetType().Name) ' Outputs "Boolean"
Console.WriteLine(result) ' Outputs "True"
Not sure what you are trying to do, but here is some code to play with. Note that I have changed the 'types' in the array to contain valid type names.
Dim DataValue As String = "True"
Dim ChangeTypeIndex() As String = {"System.Boolean", "System.Char", "System.SByte", "System.Byte", "System.Int16"}
Dim ChangeType As Type
For x As Integer = 0 To ChangeTypeIndex.Length - 1
ChangeType = Type.GetType(ChangeTypeIndex(x), True)
Next
ChangeType = Type.GetType(ChangeTypeIndex(0), True)
Dim Result As Object = CTypeDynamic(DataValue, ChangeType)

Get Length of Control.Tag

I am trying to find the length of a control's tag to determine a Boolean's value. I've tried a couple methods to get the text length of a Tag in a control and determine if it has a length of 1 or higher, but none of them seem to be working. They all end up with a System.NullReferenceException error.
Boolean = Control.Tag.ToString.Length > 1
Boolean = Control.Tag.ToString.Count > 1
Boolean = Not Control.Tag.Equals("")
Boolean = Not Control.Tag.ToString.Equals("")
Thats because your Tag is Null (or as it's called in VB Nothing).
So before you check the length of the Tag, you need to make sure it's not Nothing. e.g with:
If Control.Tag Is Nothing Then ...
Before accessing a method or property of the tag, you must make sure that the tag is not Nothing. You can do this in a single expression by using shortcut evaluation:
Dim isDefined As Boolean = Control.Tag IsNot Nothing AndAlso Control.Tag.ToString.Length > 1
Since VB 14.0 / Visual Studio 2015 you can use a Null-conditional operator
Dim isDefined As Boolean = If(Control.Tag?.ToString.Length, 0) > 1
In VB.NET you can use VB.NET specific way as the VB Runtime evaluates Nothing as an empty string which is represented by String.Empty.
In VB.NET you can assign Nothing to any variable regardless it is a value type or a reference type.
Its C# equivalent is default(T) which for reference types returns null and for value types returns the value represented by a state where all bits are zero. E.g. default(bool) returns false
So these ways are also working:
' Let's assume you set the Control.Tag property value to this variable
Dim controlTag As Object = Nothing
' Len() method can accept any Object
Dim controlTagLength As Integer = Len(controlTag)
Dim hasValueByLength As Boolean = controlTagLength > 0
' Always call Equals() method on a constant
' or on a well defined non-null value e.g. String.Empty
' to avoid NullReferenceException
Dim hasValueByInstanceEquals As Boolean = String.Empty.Equals(controlTag)
' Or you can use the static Equals() method that accepts Object
Dim hasValueByStaticEquals As Boolean = String.Equals(controlTag, String.Empty)

Nullable type with inline if cannot work together?

Given the following code:
Dim widthStr As String = Nothing
This works - width is assigned Nothing:
Dim width As Nullable(Of Double)
If widthStr Is Nothing Then
width = Nothing
Else
width = CDbl(widthStr)
End If
But this does not - width becomes 0.0 (although it seems to be logically identical code):
Dim width As Nullable(Of Double) = If(widthStr Is Nothing, Nothing, CDbl(widthStr))
Why? Is there anything I can do to make it work?
Further to Damien's answer, the clean way to do this is to not use Nothing, but New Double? instead:
Dim width As Double? = If(widthStr Is Nothing, New Double?, CDbl(widthStr))
And now that the type of the If expression is correct, this could be reduced to:
Dim width = If(widthStr Is Nothing, New Double?, CDbl(widthStr))
This all comes down to type analysis of expressions.
Nothing is a magical beast in VB.Net. It's approximately the same as default(T) in C#.
As such, when trying to determine the best type for the following:
If(widthStr Is Nothing, Nothing, CDbl(widthStr))
The third argument is of type Double. The second argument is convertible to Double (because Nothing can return the default value of value types). As such, the type of the return value of If is determined to be Double.
Only after that piece of type analysis has concluded is any attention paid to the type of the variable to which this expression is being assigned. And Double is assignable to Double? without any warnings.
There's no clean way to make your If() expression work how you expected. Because there's no equivalent to null in VB.Net. You'd need (at the least) to insert a DirectCast (or equivalent) on one side or another of the potential results of the If to force the type analysis to see Double? rather than Double.

How can I do C style casting in VB.NET?

I have a object type variable (control .Tag) that I need to cast to a structured type, and change a member in. This is a contrived but representative example:
Public Structure struct_COLOURS
Dim ILikeRed as boolean
Dim ILikeGreen as boolean
End Structure
Dim AnObject as Object = (some source that is struct_COLOURS)
DirectCast(AnObject, struct_COLOURS).ILikeRed = True ' This is not valid syntax?!
I don't remember my C syntax very well, but it would be something like this:
(struct_COLOURS*)AnObject->ILikeRed = true;
The point is I can cast an object to something and set members in the resulting cast. It seems as though DirectCast is actually a function and is not casting in the way I would interpret it.
Oddly, if you only want to retrieve a member value, you can use DirectCast:
dim YummyRed AS Boolean = DirectCast(AnObject, struct_COLOURS).ILikeRed
is just fine!
If I cannot cast the way I want, and I cannot change the use of the Tag property (so please don't suggest, it's not an option) to store these structures, what is the fastest way to set members?
It seems as though DirectCast is actually a function and is not casting in the way I would interpret it.
No, that’s wrong: DirectCast isn’t a method, it’s a real language construct, like a cast in C.
However, if you store a structure (= value type) in an object, it gets boxed and, by consequence, copied. This is causing the problem here: you’re attempting to modify a copy, not the original, boxed object.
So in order to change a member of a boxed value type object, you need to copy the object, change its value, and copy it back:
Dim tmp = DirectCast(AnObject, struct_COLOURS)
tmp.ILikeRed = True
AnObject = tmp
Incidentally, the same is true in C#, despite the superficial similarity to the C cast syntax.
That's how you should cast - with CType:
Dim myColor As Object = Nothing
Dim color As Color = CType(myColor, Color)
color.Name = "red"
Why a struct and not a class?

VB.NET generic function for checking for a value of null

I am trying to write a generic function that will check each database parameter to see if it is null, and if so, return DBNull; if not, return the object.
So here is my function:
Public Shared Function CheckForNull(ByVal obj As Object) As Object
If obj <> Nothing Then Return obj Else Return DBNull.Value
End Function
My problem is that some of the objects I am passing to the function are Nullable. So I may pass the function a Long? or Int?, but when a nullable type is passed to the function, it is converted to its value type. So if I pass a Long? that has a value of 0, the function returns DBNull because the Long? is converted to Long and a value of 0 for a Long is equivalent to Nothing. Is there anyway to make this function work for Nullable types as well?
If not, I will just fall back to using the following statements instead of one generic funciton call:
IIf(nullableVar.HasValue, nullableVar, DBNull.Value))
and
IIf(nonNullableVar IsNot Nothing , nonNullableVar, DBNull.Value))
That is not why your logic is failing. When evaluating an expression like (x=y) or (x<>y), if either argument is Nothing, VB.Net returns FALSE. Your conditional is always falling through to the ELSE clause. So instead of:
if obj <> Nothing then
try this instead:
if obj isnot nothing then