問題描述
String.IsNullOrEmpty() (String.IsNullOrEmpty())
Recently I've noticed that when we've been doing string comparisons in our .NET code we have been safeguarding against null references. This check seems unnecessary in VB.NET because it overloads the equality operator and performs this null ref check for us. Do you all agree ?
See examples below:
Dim myStringVariable As String
' Unnecessary in VB.NET
If myStringVariable Is Nothing OrElse myStringVariable = "" Then
End If
' Unnecessary in VB.NET
If String.IsNullOrEmpty(myStringVariable) Then
End If
' This will work
If myStringVariable = "" Then
End If
' Also acceptable if you don't like using hard coded constants
If myStringVariable = String.Empty Then
End If
‑‑‑‑‑
參考解法
方法 1:
Specifically for equality tests you may be right. However, equality tests are not the only thing you do with strings.
I have not done much VB.Net, but I strongly suspect that
myStringVariable.Length
will blow up if myStringVariable is null, er... Nothing.
方法 2:
It's never unnecessary to be explicit about what you're doing. If someone who is working on your code reads String.IsNullOrEmpty
they know that you meant treat null and empty the same way.
If someone who is working on your code reads myStringVariable = String.Empty
, they have to wonder if you meant to handle nulls and empties the same way or if you made an oversight.
方法 3:
You're right, combining all of those checks is hella redundant.
Why not simplify it to simply:
If String.IsNullOrEmpty(myStringVariable) Then
' do whatever
End If
(by Bobby、Eric J.、Pete Baughman、Cody Gray)