본문 바로가기
Program Language/C#

Part1. C# 첫발 내딛기(28. Null 조건 연산자 '?')

by 토담이아빠 2023. 1. 24.

Null 조건 연산자 '?'

 

C#에서 참조형 변수를 다룰 때에는 null 검사를 해야 합니다. 이는 객체 속성에 접근할 때마다 체크를 해줘야 합니다. 하지만 C#에서는 좀 더 편리한 방법을 제공합니다. 그것은 바로 Null 조건 연산자인  '?'을 사용하는 것입니다. 이번 포스팅에서는 이런 Null  조건 연산자에 대해 학습한 내용을 정리했습니다.


null 검사

 

null이란 어떤 객체도 참조하지 않는 참조형 변수입니다. 참조형 변수에 어떠한 객체도 할당되지 않았을 때 디폴트로 할당되어 있는 값이 null입니다. 다만 null은 값형에는 할당될 수 없습니다.

 

null인 참조형 변수에 접근하려고 할 경우 예외가 발생하기 때문에 객체의 생성여부를 파악하기 위해 널 검사를 많이 사용합니다.  다음은 일반적으로 사용하는 null 검사 방법입니다.


string str = null;

if(str != null && str.Length > 0)
{
    // do something...
}

Null 조건 연산자 '?' 사용

 

위와 같은 null 검사는 string 객체의 속성에 접근할 때마다 체크해주어야하는 불편함이 있습니다. C# 6.0부터는 이러한 불편함을 없애기 위해 null 조건 연산자가 '?"가 도입되었습니다. 위 예제는 Null 조건 연산자를 사용하여 다음과 같이 다시 쓸 수 있습니다.


string str = null;

if(str?.Length > 0)
{
    // do something...
}

Null 조건 연산자는 보통 멤버 연산자(.)나 인덱스 연산자[]와 같이 사용되며 피연산자 값이 null이면 null을 리턴합니다. 


int? length = customers?.Length; // customers가 null이면 null
Customer first = customers?[0];  // customers가 null이면 null

//customers나 customers[0]나 customer[0].Orders가 null이면 null
int? count = customers?[0]?.Orders?.Count();

다음은 Null 조건 연산자를 사용하여 동물 이름을 출력하는 예제입니다.


using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Runtime.Remoting.Channels;
using System.Text;
using System.Threading.Tasks;

namespace nullexam
{

    internal class Program
    {
        
        private static void LongNameAnimal(ref string animal)
        {
            if(animal?.Length >= 2) //Null 연산자 사용
            {
                Console.WriteLine(animal + " : " + animal.Length);
            }
        }
        static void Main(string[] args)
        {
            string animal = null;

            Console.WriteLine("2글자 이상 동물의 이름만 출력합니다.");
            do
            {
                LongNameAnimal(ref animal);
                Console.Write("동물 이름 : ");
            } while ((animal = Console.ReadLine()) != "");
            
        }
    }
}

결과

2글자 이상 동물의 이름만 출력합니다.
동물 이름 : lion
lion : 4
동물 이름 : tiger
tiger : 5
동물 이름 :

[Review]
"초보자를 위한 C# 200제(2판)" / 저자 : 강병익

 

 

댓글