C#/์ด๊ฒƒ์ด C#์ด๋‹ค

13. null ๋ณ‘ํ•ฉ ์—ฐ์‚ฐ์ž

Rainbow๐ŸŒˆCoder 2022. 2. 8. 12:43
728x90

a??b

a๊ฐ€ null์ด๋ฉด b ๋ฐ˜ํ™˜

null์ด ์•„๋‹ˆ๋ฉด a ๊ทธ๋Œ€๋กœ ๋ฐ˜ํ™˜

 

null ๋ณ‘ํ•ฉ ์—ฐ์‚ฐ์ž ??๋Š” null ์กฐ๊ฑด๋ถ€ ์—ฐ์‚ฐ์ž์ฒ˜๋Ÿผ ํ”„๋กœ๊ทธ๋žจ์—์„œ ์ข…์ข… ํ•„์š”ํ•œ ๋ณ€์ˆ˜/๊ฐ์ฒด์˜ null ๊ฒ€์‚ฌ๋ฅผ ๊ฐ„๊ฒฐํ•˜๊ฒŒ ๋งŒ๋“ค์–ด์ค€๋‹ค.

 

?? ์—ฐ์‚ฐ์ž๋Š” ๋‘ ๊ฐœ์˜ ํ”ผ์—ฐ์‚ฐ์ž๋ฅผ ๋ฐ›์•„๋“ค์ด๊ณ  ์™ผ์ชฝ ํ”ผ์—ฐ์‚ฐ์ž๊ฐ€ null์ธ์ง€ ํ‰๊ฐ€ํ•œ๋‹ค.

 

ํ‰๊ฐ€ ๊ฒฐ๊ณผ๊ฐ€ null์ด ์•„๋‹Œ ๊ฒƒ์œผ๋กœ ๋‚˜ํƒ€๋‚˜๋ฉด ํ”ผ์—ฐ์‚ฐ์ž๋ฅผ ๊ทธ๋Œ€๋กœ ๋ฐ˜ํ™˜ํ•˜๊ณ ,

 

null์ธ ๊ฒƒ์œผ๋กœ ํ‰๊ฐ€๋˜๋ฉด ์˜ค๋ฅธ์ชฝ ํ”ผ์—ฐ์‚ฐ์ž๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

 

<์†Œ์Šค์ฝ”๋“œ>

using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;

namespace Hello
{
    class MainApp
    {
        static void Main(string[] args)
        {
            int? num = null;
            WriteLine($"{num??0}");

            num = 99;
            WriteLine($"{num??0}");

            string str = null;
            string temp = "Default";
            WriteLine($"{str??"Default"}");

            str = "Specific";
            WriteLine($"{str?? temp}");
        }
    }
}

<์ถœ๋ ฅ>

0
99
Default
Specific
728x90