views:

250

answers:

2

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
+4  A: 

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.

rchern
Do you know the reason behind automatically converting Nothing to a string on the fly when I do the comparison? What is the benefit of this?
Ek0nomik
When using the = operator with a string, VB.NET uses StrCmp, rather than op_Equality. I'd speculate this was for backwards compatibility reasons.
rchern
+1  A: 

Try this:

Console.WriteLine("Is String.Empty equal to Nothing?: {0}", String.Empty.Equals(Nothing))

The = operator doesn't enforce equal types, whereas the .Equals() method of a string object does, as does the Is operator.

Amber