String.IsNullOrEmpty와 String.IsNullOrWhiteSpace의 차이점에 대해서 알아봅니다.

 

 

 

String.IsNullOrEmpty와 String.IsNullOrWhiteSpace

 

두 메서드는 한글로 해석하면 비어있다와 공백이다 정도의 아주 미묘한 차이로 해석됩니다. 이게 한글로 해석하면 미묘한 것이 공백의 사전적 정의에 "아무것도 없이 비어 있음."이 포함되어 있습니다. 결국 똑같이 해석되는 것처럼 보입니다. 

 

하지만 C#에서 프로그래밍적으로 두 메서드는 엄연히 다른 메서드입니다. MSDN에 따르면 String.IsNullOrWhiteSpace에 대한 설명에서 다음과 같이 나와있습니다.

 

 

 

IsNullOrWhiteSpace는 우수한 성능을 제공한다는 점을 제외하면 다음 코드와 유사한 기능을 하는 편리한 메서드입니다.

return String.IsNullOrEmpty(value) || value.Trim().Length == 0;

공백 문자는 유니 코드 표준에 의해 정의됩니다. IsNullOrWhiteSpace 메서드는 Char.IsWhiteSpace 메서드에 의해 true 값을 반환하는 모든 문자를 공백 문자로 해석합니다.

 

결국 String.IsNullOrWhiteSpace 메서드는 매개변수에 유니코드에 표준에 의한 "공백 문자"가 있더라도 true를 반환합니다. 다음 예시를 보면 그 차이를 한눈에 이해할 수 있습니다.

 

string.IsNullOrWhiteSpace("\t"); //true
string.IsNullOrEmpty("\t"); //false

string.IsNullOrWhiteSpace(" "); //true
string.IsNullOrEmpty(" "); //false

string.IsNullOrWhiteSpace("\n"); //true
string.IsNullOrEmpty("\n"); //false

 

 

 

 

 

 

반응형

+ Recent posts