Notice
Recent Posts
Recent Comments
Link
관리 메뉴

nomad-programmer

[Programming/C#] null 조건부 연산자 본문

Programming/C#

[Programming/C#] null 조건부 연산자

scii 2020. 9. 6. 21:25

널(null) 조건부 연산자 ?.는 C# 6.0에서 도입되었다. 
?. 가 하는 일은 객체의 멤버에 접근하기 전에 해당 객체가 null인지 검사하여 그 결과가 참(즉, 객체가 null)이면 그 결과로 null을 반환하고, 그렇지 않은 경우에는 . 뒤에 지정된 멤버를 반환한다. 

// == 연산자를 이용한 코드
Foo foo = null;

int? bar;
if (foo == null)
    bar = null;
else
    bar = foo.member;
    
    
// ?. 연산자를 이용한 코드
Foo foo = null;

int? bar;
bar = foo?.member;

 

?[] 연산자

?[] 연산자도 동일한 기능을 수행하는 연산자이다. ?[] 는 ?. 와 비슷한 역할을 하지만, 객체의 멤버 접근이 아닌 배열과 같은 컬렉션 객체의 첨자를 이용한 참조에 사용된다는 점이 다르다. 

using System.Collections;
using static System.Console;

namespace CSharpExam
{
    class OperExample
    {
        static int Main(string[] args)
        {
            ArrayList a = null;
            // a가 null이 아니면 a의 Add메소드를 호출하여 야구를 집어 넣으라는 뜻.
            a?.Add("야구"); // a?.이 null을 반환하므로 Add() 메소드는 호출되지 않음.
            a?.Add("축구");

            WriteLine($"Count: {a?.Count}");
            WriteLine($"{a?[0]}");
            WriteLine($"{a?[1]}");

            a = new ArrayList();
            a?.Add("야구");
            a?.Add("축구");

            WriteLine($"Count: {a?.Count}");
            WriteLine($"{a?[0]}");
            WriteLine($"{a?[1]}");

            return 0;
        }
    }
}

/* 결과

Count:


Count: 2
야구
축구

*/
Comments