Programing

C #에서 IsNullOrEmpty와 IsNullOrWhiteSpace의 차이점

crosscheck 2020. 7. 25. 10:33
반응형

C #에서 IsNullOrEmpty와 IsNullOrWhiteSpace의 차이점


이 질문에는 이미 답변이 있습니다.

C #에서 이러한 명령의 차이점은 무엇입니까?

string text= "  ";
1-string.IsNullOrEmpty(text.Trim())

2-string.IsNullOrWhiteSpace(text)

IsNullOrWhiteSpace 우수한 성능을 제공한다는 점을 제외하고는 다음 코드와 유사한 편리한 방법입니다.

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

공백 문자는 유니 코드 표준에 의해 정의됩니다. IsNullOrWhiteSpace메소드는 Char.IsWhiteSpace공백 문자로 메소드에 전달 될 때 true 값을 리턴하는 모든 문자를 해석합니다 .


첫 번째 방법은 문자열이 null인지 또는 빈 문자열인지 확인합니다. 귀하의 예에서는 다듬기 전에 null을 확인하지 않기 때문에 null 참조가 위험 할 수 있습니다

1- string.IsNullOrEmpty(text.Trim())

두 번째 방법은 문자열이 null인지 또는 문자열의 공백 수 (공백 문자열 포함)인지 확인합니다.

2- string .IsNullOrWhiteSpace(text)

이 메서드 IsNullOrWhiteSpace는를 다루지 IsNullOrEmptytrue문자열에 공백이 포함되어 있으면 반환 합니다.

구체적인 예제에서는 2) null 일 수있는 문자열에서 trim을 호출하기 때문에 접근법 1)에서 null 참조 예외의 위험을 실행할 때 2를 사용해야합니다.


공간 , 탭 \t및 줄 바꿈 \n은 차이점입니다.

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

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

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

https://dotnetfiddle.net/4hkpKM

또한 다음에 대한 답변을 참조하십시오 : 공백 문자


String.IsNullOrEmpty(string value)true문자열이 null이거나 비어있는 경우를 반환 합니다. 참조를 위해 빈 문자열은 ""(큰 따옴표 두 개)로 표시됩니다.

String.IsNullOrWhitespace(string value)true문자열이 null이거나 비어 있거나 공백 또는 탭과 같은 공백 문자 만 포함하는 경우를 반환 합니다.

공백으로 간주되는 문자를 확인하려면 다음 링크를 참조하십시오. http://msdn.microsoft.com/en-us/library/t809ektx.aspx


이것은 디 컴파일 후 메소드의 구현입니다 .

    public static bool IsNullOrEmpty(String value) 
    {
        return (value == null || value.Length == 0); 
    }

    public static bool IsNullOrWhiteSpace(String value) 
    {
        if (value == null) return true; 

        for(int i = 0; i < value.Length; i++) { 
            if(!Char.IsWhiteSpace(value[i])) return false; 
        }

        return true;
    }

따라서 IsNullOrWhiteSpace 메서드는 전달되는 값에 공백이 포함되어 있는지 확인합니다.

공백 참조 : https://msdn.microsoft.com/en-us/library/system.char.iswhitespace(v=vs.110).aspx


문자열 (귀하의 경우 변수 text)이 null 인 경우 큰 차이가 발생합니다.

null 객체의 mthode를 호출 한 이후 1 string.IsNullOrEmpty(text.Trim())--> EXCEPTION

2-string.IsNullOrWhiteSpace(text) This would work fine since the null issue is beeing checked internally

To provide the same behaviour using the 1st Option you would have to check somehow if its not null first then use the trim() method

if ((text != null) && string.IsNullOrEmpty(text.Trim())) { ... }

string.isNullOrWhiteSpace(text) should be used in most cases as it also includes a blank string.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //Your code goes here
            var str = "";

            Console.WriteLine(string.IsNullOrWhiteSpace(str));              

        }
    }
}

It returns True!


[Performance Test] just in case anyone is wondering, in a stopwatch test comparing

if(nopass.Trim().Length > 0)

if (!string.IsNullOrWhiteSpace(nopass))



these were the results:

Trim-Length with empty value = 15

Trim-Length with not empty value = 52


IsNullOrWhiteSpace with empty value = 11

IsNullOrWhiteSpace with not empty value = 12

참고URL : https://stackoverflow.com/questions/18710644/difference-between-isnullorempty-and-isnullorwhitespace-in-c-sharp

반응형