C# 널 조건부 연산자
제럴드 베르슬루이스는 자신의 영상 중 하나에서 샘플 코드에 있는 물음표(?)에 대한 질문을 받았습니다. 이로 인해 그는 C#의 null 조건 연산자를 자세히 설명하는 비디오를 제작하게 되었습니다. C#에서 ?. 또는 ?[ ]가 무엇을 하는지 궁금했다면, Gerald의 동영상은 이를 명확히 이해하는 데 좋은 리소스입니다. 그의 설명을 단계별로 살펴보겠습니다.
Docs 페이지를 통한 간략한 설명
제럴드는 멤버 액세스 연산자와 표현식에 대한 마이크로소프트의 공식 문서를 참조하는 것으로 이야기를 시작합니다. 그는 C# 6에서 도입된 null 조건 연산자에 대한 부분을 강조합니다. 녹화 당시에는 C# 9가 최신 버전이었고, C# 10이 출시될 예정이었습니다.
Gerald는 a?.x 또는 a?[index]를 사용할 때, a가 null이면 전체 표현식이 NullReferenceException을 던지는 대신 null로 평가된다고 설명합니다. 그렇지 않으면 값을 정상적으로 가져옵니다.
문서도 도움이 되지만, 제럴드는 직접 실습하는 예시를 선호하기 때문에 대화형 코딩 환경으로 이동합니다.
.NET 통한 예시
이를 시연하기 위해 제럴드는 대화형 C# 환경인 .NET 으로 전환합니다. 그는 이 도구가 Blazor 에서 실행되므로 사용자가 브라우저에서 C# 코드를 직접 실행할 수 있다고 언급합니다.
그는 .NET 에 미리 로드된 기본 피보나치 수열 예제를 간략하게 보여준 다음, 해당 예제를 지우고 null 조건 연산자에 초점을 맞춘 새로운 예제를 시작합니다.
널 조건 연산자 설명
제럴드는 다음과 같은 속성을 가진 간단한 Person 클래스를 만듭니다.
public class Person
{
// The Name property of the Person
public string Name { get; set; }
// A reference to another Person object representing the partner
public Person Partner { get; set; }
// An array representing the Person's hobbies
public string[] Hobbies { get; set; }
}public class Person
{
// The Name property of the Person
public string Name { get; set; }
// A reference to another Person object representing the partner
public Person Partner { get; set; }
// An array representing the Person's hobbies
public string[] Hobbies { get; set; }
}그는 Person 객체를 null로 초기화합니다:
// Initialize a Person object as null
Person person = null;
// Attempting to access a property of a null object will throw a NullReferenceException
Console.WriteLine(person.Name);// Initialize a Person object as null
Person person = null;
// Attempting to access a property of a null object will throw a NullReferenceException
Console.WriteLine(person.Name);이 코드를 실행하면 person가 null이기 때문에 NullReferenceException이 발생합니다. 이를 방지하기 위해 개발자는 일반적으로 속성에 접근하기 전에 null 검사를 추가합니다.
// Check if the person object is not null before accessing its properties
if (person != null)
{
Console.WriteLine(person.Name);
}// Check if the person object is not null before accessing its properties
if (person != null)
{
Console.WriteLine(person.Name);
}이 방법은 효과가 있지만, 코드 줄이 하나 더 늘어납니다. 제럴드는 널 조건 연산자가 이를 어떻게 단순화하는지 설명합니다.
// Using the null-conditional operator to safely access the Name property
Console.WriteLine(person?.Name);// Using the null-conditional operator to safely access the Name property
Console.WriteLine(person?.Name);이제, person가 null이면 표현식은 충돌하는 대신 단순히 null을 반환합니다.
속성에 대한 null 조건 연산자
Gerald는 Person 객체를 설정하여 예제를 확장합니다:
// Create a new Person object
Person person = new Person { Name = "Gerald" };
// Access the Name property safely
Console.WriteLine(person?.Name);// Create a new Person object
Person person = new Person { Name = "Gerald" };
// Access the Name property safely
Console.WriteLine(person?.Name);person가 null이 아니기 때문에 올바르게 "Gerald"를 출력합니다.
다음으로, 그는 중첩된 예제를 보여줍니다.
// Safely access the Name property of the Partner object
Console.WriteLine(person?.Partner?.Name);// Safely access the Name property of the Partner object
Console.WriteLine(person?.Partner?.Name);person.Partner가 null이면 전체 표현식은 예외를 던지는 대신 null로 평가됩니다. 이렇게 하면 불필요한 조건문을 피할 수 있습니다.
널 조건 연산자 연결
제럴드는 널 조건 연산자를 연결하여 사용할 수 있으므로, 깊이 중첩된 객체를 다룰 때 코드를 더 깔끔하게 만들 수 있다고 설명합니다. 여러 개의 null 검사를 작성하는 대신 다음을 사용할 수 있습니다.
// Chain null-conditional operators to safely access nested objects
Console.WriteLine(person?.Partner?.Name);// Chain null-conditional operators to safely access nested objects
Console.WriteLine(person?.Partner?.Name);person 또는 person.Partner가 null이면 결과는 null이 되어 런타임 오류를 방지합니다.
배열에 대한 널 조건 연산자
제럴드는 논의를 배열과 컬렉션 으로 확장합니다. 그는 Person 클래스에 Hobbies 배열을 추가하고 요소에 안전하게 접근하는 방법을 보여줍니다.
// Safely access the first element of the Hobbies array
Console.WriteLine(person?.Hobbies?[0]);// Safely access the first element of the Hobbies array
Console.WriteLine(person?.Hobbies?[0]);여기에서 person 또는 Hobbies가 null이면 표현식은 예외를 일으키는 대신 null로 평가됩니다.
결론
제럴드의 영상은 C#의 null 조건 연산자에 대해 심층적으로 다룹니다. ?. 및 ?[ ]를 사용함으로써 개발자는 NullReferenceException을 피하고 더 간결하고 안전한 코드를 작성할 수 있습니다. 속성, 중첩 객체 또는 배열을 다룰 때, null 조건 연산자를 사용하면 코드가 더 간결하고 읽기 쉬워집니다.
자세한 내용을 확인하시려면 제럴드 베르슬루이스의 영상을 시청해 보세요. 실제 사례를 통해 모든 것을 설명해 드립니다!

