Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB setting a string to nothing [duplicate]

Tags:

vb.net

The code below returns TRUE when I expected it to return FALSE.

Why does it return TRUE? I Expect nothing to set the value of the string to null, not empty (According to msdn)

CodeingGround sample

Module VBModule

    Sub Main()
        dim x as String
        x = nothing
        console.writeline(x = string.Empty)
    End Sub

End Module

Nothing (Visual Basic)

Represents the default value of any data type. For reference types, the default value is the null reference.

***EDIT**** Nothing = String.Empty (Why are these equal?)

Nothing in VB.net is the default value for a type. The language spec says in section 2.4.7:

Nothing is a special literal; it does not have a type and is convertible to all types in the type system, including type parameters. When converted to a particular type, it is the equivalent of the default value of that type.

So, when you test against String.Empty, Nothing is converted to a string, which has a length 0. The Is operator should be used for testing against Nothing, and String.Empty.Equals(Nothing) will also return false.

Per then comment,

when converted to a particular type, it is the equivalent of the default value of that type.

The default value for a string is null. I dont understand why that answer was accepted.

like image 431
gh9 Avatar asked Jul 22 '15 14:07

gh9


People also ask

How do you empty a string in VB?

For strings in Visual Basic, the empty string equals Nothing . Therefore, "" = Nothing is true. This means that MyString = String. Empty will be true when MyString Is Nothing is also true.

Is VB nothing same as null?

When checking whether a reference (or nullable value type) variable is null , do not use = Nothing or <> Nothing . Always use Is Nothing or IsNot Nothing . For strings in Visual Basic, the empty string equals Nothing .

What is null in Visual Basic?

In Visual Basic 6.0, the Null keyword indicated that a field contained no valid data, and the IsNull function was used to test for Null.

What is string in VB?

In VB.NET, string is a sequential collection of characters that is called a text. The String keyword is used to create a string variable that stores the text value. The name of the string class is System.


Video Answer


1 Answers

Difference between C# and VB.Net string comparison

The above post explains the answer clearly, credit goes to Tim Schmelter in the comment section for finding the above post

Per Tim Schmeleters comments

it is called from the vb compiler as the documentation states in String.Equality Operator

like image 132
gh9 Avatar answered Oct 13 '22 11:10

gh9