C#에서 문자열을 초기화할 때 null 또는 string.Empty를 사용하여 빈 문자열 상태로 만들 수 있습니다. 이 글에서는 두 가지 방법과 함께 IsNullOrEmpty() 메서드를 활용해 문자열이 비어 있는지 확인하는 방법을 알아보겠습니다.
1. null로 초기화하기
가장 먼저 소개할 방법은 문자열을 null 값으로 초기화하는 것입니다.
string myStr = null;
이후 내장 메서드인 IsNullOrEmpty()를 사용하면 해당 문자열이 비어 있거나 null인지 손쉽게 확인할 수 있습니다.
if (string.IsNullOrEmpty(myStr)) {
Console.WriteLine("문자열이 비어 있거나 null입니다!");
}예제 코드
전체 코드를 통해 동작 과정을 살펴보겠습니다.
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
string myStr = null;
if (string.IsNullOrEmpty(myStr)) {
Console.WriteLine("String is empty or null!");
}
Console.ReadKey();
}
}
}실행 결과
String is empty or null!
2. string.Empty로 초기화하기
문자열을 빈 문자열로 초기화하는 또 다른 방법은 string.Empty를 사용하는 것입니다. 아래 예제에서는 if-else 문을 활용해 문자열의 상태에 따라 다른 결과를 출력합니다.
예제 코드
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!
null과 string.Empty의 차이점
두 방식 모두 IsNullOrEmpty() 메서드에서 "비어 있음"으로 판단되지만, 의미상 차이가 있습니다. null은 문자열 객체 자체가 존재하지 않는 상태를 의미하고, string.Empty는 길이가 0인 유효한 문자열 객체를 나타냅니다. 일반적으로 메모리 할당 없이 안전하게 초기화하려면 string.Empty 사용을 권장하며, NullReferenceException 발생 위험을 줄일 수 있습니다.