System.String.IsNullOrEmpty メソッド

この記事では、この API のリファレンス ドキュメントへの補足的な解説を提供します。

IsNullOrEmptyは便利なメソッドであり、is またはその値String.Emptyが 〘 かどうかをStringnull同時にテストできます。 これは、次のコードと同じです。

bool TestForNullOrEmpty(string s)
{
    bool result;
    result = s == null || s == string.Empty;
    return result;
}

string s1 = null;
string s2 = "";
Console.WriteLine(TestForNullOrEmpty(s1));
Console.WriteLine(TestForNullOrEmpty(s2));

// The example displays the following output:
//    True
//    True
result = s Is Nothing OrElse s = String.Empty
let testForNullOrEmpty (s: string): bool =
    s = null || s = String.Empty

let s1 = null
let s2 = ""

printfn "%b" (testForNullOrEmpty s1)
printfn "%b" (testForNullOrEmpty s2)

// The example displays the following output:
//    true
//    true

このメソッドを IsNullOrWhiteSpace 使用して、文字列が null文字列であるか、その値が String.Empty空白文字のみで構成されているかをテストできます。

null 文字列とは

文字列は、 null 値が (C++ および Visual Basic で) 割り当てられていない場合、または明示的に値 nullが割り当てられている場合です。 複合書式指定機能は null 文字列を適切に処理できますが、次の例に示すように、メンバーNullReferenceExceptionが .

  String s = null;

  Console.WriteLine("The value of the string is '{0}'", s);

  try 
  {
      Console.WriteLine("String length is {0}", s.Length);
  }
  catch (NullReferenceException e) 
  {
      Console.WriteLine(e.Message);
  }

  // The example displays the following output:
  //     The value of the string is ''
  //     Object reference not set to an instance of an object.
Module Example
   Public Sub Main()
      Dim s As String

      Console.WriteLine("The value of the string is '{0}'", s)

      Try 
         Console.WriteLine("String length is {0}", s.Length)
      Catch e As NullReferenceException
         Console.WriteLine(e.Message)
      End Try   
   End Sub
End Module
' The example displays the following output:
'     The value of the string is ''
'     Object reference not set to an instance of an object.
let (s: string) = null

printfn "The value of the string is '%s'" s

try
    printfn "String length is %d" s.Length
with
    | :? NullReferenceException as ex -> printfn "%s" ex.Message

// The example displays the following output:
//     The value of the string is ''
//     Object reference not set to an instance of an object.

空の文字列とは

文字列が明示的に空の文字列 ("") または String.Empty. 空の文字列の値は Length 0 です。 次の例では、空の文字列を作成し、その値とその長さを表示します。

String s = "";
Console.WriteLine("The length of '{0}' is {1}.", s, s.Length);

// The example displays the following output:
//       The length of '' is 0.
Dim s As String = ""
Console.WriteLine("The length of '{0}' is {1}.", s, s.Length)
' The example displays the following output:
'        The length of '' is 0.
let s = ""
printfn "The length of '%s' is %d." s s.Length

// The example displays the following output:
//       The length of '' is 0.