IsNullOrEmpty

 

String 이 null 이거나 empty 이면 true를 반환하고, 그렇지 않으면 false를 반환합니다.

 

함수 형태는 다음과 같습니다.

 public static bool IsNullOrEmpty([NotNullWhen(false)] String? value);
 
 매개변수
 value String
 
 반환
 Boolean

null 인지 empty 인지 일일이 체크하려고 하면 조건문이 많이 생기게 되어서 생각보다 프로그램이 커질 때 복잡해질 수 있는데, String 클래스의 IsNullOrEmpty 메서드를 사용하면 간단하게 한 번에 체크가 가능합니다.

 

사용법은 String 클래스에서 static 메서드인 IsNullOrEmpty를 호출하면 됩니다.

 

String 은 총 3가지 형태로 존재하게 되는데,

string a = "문자열";
string b = "";
string c = null;

문자열을 담을 수 있고,

빈 문자열 ("")와 같이 길이가 0인 문자열을 담을 수 있고,

초기화를 하지 않게 되면 default 인자로 null을 담게 됩니다.

 

주의할 점은 빈 문자열("")은 String.Length 호출에는 문제가 없지만,

null인 문자열은 String.Length 호출하게 되면 아래와 같은 에러를 얻을 수 있습니다.

Object reference not set to an instance of an object.
Null 문자열이란?

 

문자열에서 null 값이 할당되지 않은 경우 이거나, 명시적으로 할당된 경우입니다.

연습 소스 코드
class Program
{
    static void CheckString(string s)
    {
        if (true == String.IsNullOrEmpty(s))
            Console.WriteLine("is null or empty");
        else
            Console.WriteLine(s + " is string!");
    }
    static void Main()
    {
        string s1 = "hello";
        string s2 = "";
        string s3 = null;

        Console.WriteLine($"s1 : {s1}");
        Console.WriteLine($"s2 : {s2}");
        Console.WriteLine($"s3 : {s3}");

        CheckString(s1);
        CheckString(s2);
        CheckString(s3);

        Console.WriteLine($"s2 length : {s2.Length}");
        try
        {
            Console.WriteLine($"s3 length : {s3.Length}");
        }
        catch(NullReferenceException e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

'CS > C#' 카테고리의 다른 글

[C#] 클래스  (0) 2021.12.11
[C#] 문자열 찾기 함수들  (0) 2021.12.10
[C#] var  (0) 2021.12.10
[C#] foreach  (0) 2021.12.05
[C#] null 병합 연산자, ??  (0) 2021.12.05

+ Recent posts