38.16 속성에서 ?.와 ?? 연산자를 함께 사용하기
개체에 들어 있는 속성 값이 null일 때는 전에 살펴본 ?.와 ?? 연산자를 사용하여 null 값을 편리하게 처리할 수 있습니다. 다음 코드는 조금 복잡하니 한 번 정도 작성하여 실행한 후 넘어갑니다.
속성 값이 null일 때 ?.와 ?? 연산자를 함께 사용: NullWithObject.cs
using System.Collections.Generic;
using static System.Console;
namespace NullWithObject
{
class Person
{
public string Name { get; set; }
public Address Address { get; set; }
}
class Address
{
public string Street { get; set; } = "알 수 없음";
}
class NullWithObject
{
static void Main()
{
var people = new Person[] { new Person { Name = "RedPlus" }, null };
ProcessPeople(people);
void ProcessPeople(IEnumerable<Person> peopleArray)
{
foreach (var person in peopleArray)
{
//① ?.로 null을 확인하여 null이면 ?? 이후의 문자열로 초기화
WriteLine($"{person?.Name ?? "아무개"}은(는) " +
$"{person?.Address?.Street ?? "아무곳"}에 삽니다.");
}
}
var otherPeople = null as Person[];
//② ?[0] 형태로 인덱서에 대해 null 값 확인 가능
WriteLine($"첫 번째 사람 : {otherPeople?[0]?.Name ?? "없음"}");
}
}
}