null 연산자: ?., ?[], ??

Fruit·2023년 3월 28일

✨ Hello C#!

목록 보기
11/34
post-thumbnail

🌸 null 조건부 연산자: ?., ?[]

  • 객체가 null인지 검사하여 null 이면 null 을, null이 아닌 경우 . 뒤에 지정된 멤버를 반환한다.

?.

using System;
using System.Collections;

namespace NullConditionalOperator
{
    class MainApp
    {
        public int member;
        static void Main(string[] args)
        {
            MainApp foo = null;

            int? bar;
            bar = foo?.member;		// foo 객체가 null 이 아니면 memeber 반환

            //  bar = foo?.member; 와 동일한 코드
            if (foo != null)
                bar = null;
            else
                bar = foo?.member;
        }
    }
}

?[]

using System;
using System.Collections;

namespace NullConditionalOperator
{
    class MainApp
    {
        static void Main(string[] args)
        {
            ArrayList a = null;

            a?.Add("Hello");		// a?.: null 반환 → Add() 메소드 호출 X
            a?.Add("Fruit!");

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

            a = new ArrayList();

            a?.Add("Hello");
            a?.Add("Fruit!");

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

[실행 결과]
Count:
a?[0]:
a?[1]:

Count: 2
a?[0]: Hello
a?[1]: Fruit!



🌸 null 병합 연산자: ??

  • 객체가 null인지 검사하여 null 이면 오른쪽 피연산자를, null이 아닌 경우 왼쪽 피연산자를 그대로 반환한다.
using System;

namespace NullConditionalOperator
{
    class MainApp
    {
        static void Main(string[] args)
        {
            int? num = null;

            Console.WriteLine($"{num ?? 10}");

            num = 99;
            Console.WriteLine($"{num ?? 10}");

            string str = null;
            Console.WriteLine($"{str ?? "str = null"}");

            str = "Hello Fruit!";
            Console.WriteLine($"{str ?? "str = null"}");
        }
    }
}

[실행 결과]
10
99
str = null
Hello Fruit!

▪ 참고: Hello Fruit! - Nullable

▪ 사진 출처: Pixabay - Arek Socha

profile
🌼인생 참 🌻꽃🌻 같다🌼

0개의 댓글