Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C#에서 string.Empty로 빈 문자열을 초기화하는 방법

C#에서는 string.Empty를 사용하여 문자열 변수를 빈 값으로 초기화할 수 있습니다. 이는 큰따옴표 두 개("")를 사용하는 것과 동일한 결과를 내지만, 코드의 의도를 더 명확하게 표현할 수 있다는 장점이 있습니다.

string myStr = string.Empty;

null 또는 빈 문자열 확인하기

초기화된 문자열이 null이거나 비어 있는지 확인하려면 IsNullOrEmpty() 메서드를 사용합니다. 이 메서드는 문자열이 null이거나 길이가 0인 경우 true를 반환합니다.

if (string.IsNullOrEmpty(myStr)) {
    Console.WriteLine("문자열이 비어 있거나 null입니다!");
}

전체 예제 코드

다음은 string.Empty로 문자열을 초기화하고, IsNullOrEmpty()로 상태를 확인하는 전체 예제입니다.

using System;

namespace Demo {
    public class Program {
        public static void Main(string[] args) {
            string myStr = string.Empty;

            if (string.IsNullOrEmpty(myStr)) {
                Console.WriteLine("String is empty or null!");
            } else {
                Console.WriteLine("String isn't empty or null!");
            }
        }
    }
}

실행 결과

String is empty or null!

myStr 변수가 string.Empty로 초기화되었기 때문에 조건문이 true가 되어 "String is empty or null!"이라는 메시지가 출력됩니다.

참고 사항

string.EmptyString.Empty는 완전히 동일합니다. string은 C#의 키워드이고 String은 .NET의 클래스 이름일 뿐, 둘 다 같은 타입을 가리킵니다. 다만 C# 관례상 소문자 키워드인 string.Empty를 사용하는 것이 일반적입니다.