System.String.IsNullOrEmpty 메서드

이 문서에서는 이 API에 대한 참조 설명서에 대한 추가 설명서를 제공합니다.

IsNullOrEmpty 는 값이 있는지 여부를 동시에 테스트할 수 있는 Stringnull 편리한 메서드입니다 String.Empty. 다음 코드와 동일합니다.

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 문자열을 정상적으로 처리할 수 있지만 멤버가 null을 throw하는 경우 하나를 호출하려고 시도합니다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.을 명시적으로 할당한 경우 비어 있습니다. 빈 문자열의 값은 0입니다 Length . 다음 예제에서는 빈 문자열을 만들고 해당 값과 길이를 표시합니다.

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.