Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Why does the first if statement evaluate to true? I know if I use "is" instead of "=" then it won't evaluate to true. If I replace String.Empty with "Foo" it doesn't evaluate to true. Both String.Empty and "Foo" have the same type of String, so why does one evaluate to true and the other doesn't?

    //this evaluates to true     If Nothing = String.Empty Then      End If      //this evaluates to false     If Nothing = "Foo" Then      End If 
like image 458
Justin Helgerson Avatar asked Apr 13 '10 21:04

Justin Helgerson


People also ask

Is empty string equal?

An empty string is a String object with an assigned value, but its length is equal to zero.

What does it mean if a string is empty?

An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .

Is an empty string the same as none?

None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.

What is the difference between string empty and string empty in C#?

Empty is a readonly field while "" is a const. This means you can't use String. Empty in a switch statement because it is not a constant.


2 Answers

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.

like image 174
Rebecca Chernoff Avatar answered Sep 28 '22 18:09

Rebecca Chernoff


It's a special case of VB's = and <> operators.

The Language Specification states in Section 11.14:

When doing a string comparison, a null reference is equivalent to the string literal "".


If you are interested in further details, I have written an in-depth comparison of vbNullString, String.Empty, "" and Nothing in VB.NET here:

  • https://stackoverflow.com/a/34069187/87698
like image 32
Heinzi Avatar answered Sep 28 '22 18:09

Heinzi