开发者

Nothing equals String.Empty, null does not equal String.Empty, what am I missing here?

In a mixed code project (VB and C#) we were debugging some old Visual Basic code like this:

If Request.Params("xxx") <> "" Then
   'do something

I considered this a bug as Request.Params could be null, in which case the statement would've become false which wasn't the idea.

So I thought. I just found out -- again -- that VB's Nothing and C#'s null are not the same things and Nothing is not the same as null. In fact:

if(String.Empty == null)          // in C# this is always false (correct)
If String.Empty = Nothing Then    ' in VB this is always true (????)

How i开发者_如何学Cs this even possible? Is this some backward compatibility issue?


Nothing has a special meaning in VB for strings. To test whether a string reference is null, you need:

If value Is Nothing

From the VB comparison operators documentation:

Numeric comparisons treat Nothing as 0. String comparisons treat Nothing as "" (an empty string).

I suspect this is just for backward compatibility with VB6 - it's not something I'd be happy with, if I were a VB developer.

A comparison of the form

If value = Nothing

is compiled to a call to Microsoft.VisualBasic.CompilerServices.Operators.CompareString which returns 0 (i.e. equal) if one operand is null and the other is empty.


In vb6, the default value for a string variable was an empty string. A vb6 programmer relying upon such behavior would be no "worse" than a C programmer relying upon default-zero initialization of int variables; both behaviors were specified as part of the language.

Further, in COM (the framework upon which previous versions of VB6 were based), any time a reference to string was created, someone would have to manually dispose of it. Since the most commonly used string was the empty string, many COM methods are explicitly documented as regarding a null pointer as equivalent to an empty string. This means that a function returning an empty string or passing one as a value parameter or returning one may simply pass a null pointer without having to allocate anything; the recipient of the null pointer will then not have to de-allocate anything.

Because Objects in .net do not require explicit deallocation, the performance advantages of regarding a null reference as an empty string no longer apply. Nonetheless, methods which are called from code that might expect behavior similar to that of COM methods will often regard null string references as being the same as empty strings.


You want

If Not String.IsNullOrEmpty(Request.Params("xxx") Then
    ...
End If

Or

if (!String.IsNullOrEmpty(Request.Params("xxx")) {
    ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜