小池啓仁 ヒロヒト応援ブログ By はてな

小池啓仁(コイケヒロヒト)の動画など。

小池啓仁 ヒロヒト応援ブログ By はてな

VB.NETでの空文字列("")は、EmptyやNothingとイコールか?

VB.NETでの空文字列("")は、EmptyやNothingとイコールか?
とりあえず、If文では、すべてイコールです。

厳密には

String.Empty フィールドは

空の文字列を表します。

http://msdn2.microsoft.com/ja-jp/library/system.string.empty(VS.80).aspx

Nothingキーワードは

変数に Nothing を代入すると、変数の宣言された型に対する既定値が変数に設定されます。
型に変数のメンバが含まれている場合は、すべてに既定値が設定されます。

http://msdn2.microsoft.com/ja-jp/library/0x9tb07z(VS.80).aspx

空文字列("")がEmptyやNothingとすべてイコールになる確証。

Dim str As String
Dim strNothing As String = Nothing
Dim strTest As String = ""
Dim strEmpty As String = String.Empty

'str
Console.WriteLine(str Is Nothing)     ←True
Console.WriteLine(str Is String.Empty)  ←False
If str = "" Then             ←True
   Console.WriteLine(True)
Else
   Console.WriteLine(False)
End If

'strNothing
Console.WriteLine(strNothing Is Nothing)    ←True
Console.WriteLine(strNothing Is String.Empty) ←False
If strNothing = "" Then            ←True
   Console.WriteLine(True)
Else
   Console.WriteLine(False)
End If

'strTest
Console.WriteLine(strTest Is Nothing)    ←False
Console.WriteLine(strTest Is String.Empty) ←True
If strTest = "" Then            ←True
   Console.WriteLine(True)
Else
   Console.WriteLine(False)
End If

'strEmpty
Console.WriteLine(strEmpty Is Nothing)    ←False
Console.WriteLine(strEmpty Is String.Empty) ←True
If strEmpty = "" Then            ←True
   Console.WriteLine(True)
Else
   Console.WriteLine(False)
End If
http://vbnet-iku2.hp.infoseek.co.jp/cgi-bin/treecrsdx02/index.cgi?m=look&bnum=1806