[ VB.NET / C# 入門 ] null または String.Empty であるか判定する ( string.IsNullOrEmpty )

Pocket

C# および VB.NET では、空文字列 ( string.Empty ) と null ( VB.NET では Nothing ) は区別されます。全くの別物です。ただ、プログラミングを行う上ではどちらの場合も同じように扱いたい場面に遭遇します。

好ましい例ではありませんが、各プログラマが好き勝手にプログラミングすると、同じように扱いたくなる(扱わざるを得ない)ことがあります。

スポンサーリンク

IsNullOrEmpty 関数: null または空文字列か調べる

string.IsNullOrEmpty 関数は null、または空文字列である場合に真を返します。また、サンプル内では、string.IsNullOrWhiteSpace 関数の使用例も記載していますが、全角スペースと半角スペースは区別されない結果となりました。詳細はサンプル内のコメントを参照ください。

VB.NET

Dim str1 As String = Nothing
Dim str2 As String = String.Empty
Dim str3 As String = "    " ' 半角スペース+全角スペース
Dim str4 As String = "   "    ' 半角スペースのみ 

If (str2 Is Nothing) Then
    ' Nothing と String.Empty は区別される
    Console.WriteLine("str2 equals Nothing")  ' 出力されない
End If

' null または空文字列の場合は True
Console.WriteLine(String.IsNullOrEmpty(str1))   ' True
Console.WriteLine(String.IsNullOrEmpty(str2))   ' True
Console.WriteLine(String.IsNullOrEmpty(str3))   ' False
Console.WriteLine(String.IsNullOrEmpty(str4))   ' False

' null または空文字列、またはスペースのみの文字列の場合は True
' 半角・全角スペースは区別されない
Console.WriteLine(String.IsNullOrWhiteSpace(str1))   ' True
Console.WriteLine(String.IsNullOrWhiteSpace(str2))   ' True
Console.WriteLine(String.IsNullOrWhiteSpace(str3))   ' True
Console.WriteLine(String.IsNullOrWhiteSpace(str4))   ' True

C#

string str1 = null;
string str2 = string.Empty;
string str3 = "    "; // 半角スペース+全角スペース
string str4 = "   ";    // 半角スペースのみ 

if(str2 == null)
{
    // null と String.Empty は区別される
    Console.WriteLine("str2 equals null"); // 出力されない
}

// null または空文字列の場合は True
Console.WriteLine(string.IsNullOrEmpty(str1)); // True
Console.WriteLine(string.IsNullOrEmpty(str2)); // True
Console.WriteLine(string.IsNullOrEmpty(str3)); // False
Console.WriteLine(string.IsNullOrEmpty(str4)); // False

// null または空文字列、またはスペースのみの文字列の場合は True
// 半角・全角スペースは区別されない
Console.WriteLine(string.IsNullOrWhiteSpace(str1)); // True
Console.WriteLine(string.IsNullOrWhiteSpace(str2)); // True
Console.WriteLine(string.IsNullOrWhiteSpace(str3)); // True
Console.WriteLine(string.IsNullOrWhiteSpace(str4)); // True

スポンサーリンク


Pocket

Leave a Comment

Your email address will not be published. Required fields are marked *