C#에는 null 값을 처리하기 위해 다음 세 가지 연산자가 있습니다. -
널 병합 연산자(??)
null이 아닌 경우 변수 값을 가져오거나 사용할 수 있는 기본값을 지정할 수 있습니다.
C#에서 다음 표현식을 대체합니다. −
string resultOne = value != null ? value : "default_value";
다음 표현식으로 -
string resultTwo = value ?? "default_value";
다음은 이를 보여주는 예입니다.
예
using System;
class Program{
static void Main(){
string input = null;
string choice = input ?? "default_choice";
Console.WriteLine(choice); // default_choice
string finalChoice = choice ?? "not_chosen";
Console.WriteLine(finalChoice); // default_choice
}
} 널 병합 할당 연산자(??=)
null이 아니면 왼쪽에 있는 값을 반환합니다. 그렇지 않으면 오른쪽에 있는 값을 반환합니다. 즉, 현재 값이 null인 경우 변수를 기본값으로 초기화할 수 있습니다.
C#에서 다음 표현식을 대체합니다. −
if (result == null) result = "default_value";
다음 표현으로.
result ??= "default_value";
이 연산자는 느리게 계산된 속성에 유용합니다. 예를 들어 -
예
class Tax{
private Report _lengthyReport;
public Report LengthyReport => _lengthyReport ??= CalculateLengthyReport();
private Report CalculateLengthyReport(){
return new Report();
}
} 널 조건부 연산자(?.)
이 연산자를 사용하면 인스턴스의 메서드를 안전하게 호출할 수 있습니다. 인스턴스가 null이면 NullReferenceException을 throw하는 대신 null을 반환합니다. 그렇지 않으면 단순히 메서드를 호출합니다.
C#에서 다음 표현식을 대체합니다. −
string result = instance == null ? null : instance.Method();
다음 식으로 -
string result = instance?.Method();
다음 예를 고려하십시오.
예
using System; string input = null; string result = input?.ToString(); Console.WriteLine(result); // prints nothing (null)
예
using System;
class Program{
static void Main(){
string input = null;
string choice = input ?? "default_choice";
Console.WriteLine(choice); // default_choice
string finalChoice = choice ?? "not_chosen";
Console.WriteLine(finalChoice); // default_choice
string foo = null;
string answer = foo?.ToString();
Console.WriteLine(answer); // prints nothing (null)
}
} 출력
default_choice default_choice