C#/์ด๊ฒ์ด C#์ด๋ค
11. null ์กฐ๊ฑด๋ถ ์ฐ์ฐ์
Rainbow๐Coder
2022. 2. 8. 11:00
728x90
๋null ์กฐ๊ฑด๋ถ ์ฐ์ฐ์ ?.๋ C# 6.0์์ ๋์ ๋์๋ค.
?.๊ฐ ํ๋ ์ผ์ ๊ฐ์ฒด์ ๋ฉค๋ฒ์ ์ ๊ทผํ๊ธฐ ์ ์ ํด๋น ๊ฐ์ฒด๊ฐ null์ธ์ง ๊ฒ์ฌํ์ฌ
๊ทธ ๊ฒฐ๊ณผ๊ฐ ์ฐธ(์ฆ, ๊ฐ์ฒด๊ฐ null)์ด๋ฉด ๊ทธ ๊ฒฐ๊ณผ๋ก null์ ๋ฐํํ๊ณ ,
๊ทธ๋ ์ง ์์ ๊ฒฝ์ฐ์๋ . ๋ค์ ์ง์ ๋ ๋ฉค๋ฒ๋ฅผ ๋ฐํํ๋ค.
| ==์ฐ์ฐ์๋ฅผ ์ด์ฉํ ์ฝ๋ | ?. ์ฐ์ฐ์๋ฅผ ์ด์ฉํ ์ฝ๋ |
| class Foo { public int member; } Foo foo = null; int?bar; if(foo==null) bar = null; else bar = foo.member; |
class Foo { public int member; } Foo foo = null; int? bar; bar = foo?.member; //foo ๊ฐ์ฒด๊ฐ null์ด ์๋๋ฉด member ํ๋์ ์ ๊ทผํ๊ฒ ํด์ค |
?[]๋ ๋์ผํ ๊ธฐ๋ฅ์ ์ํํ๋ ์ฐ์ฐ์์ด๋ค.
?[]๋ ?.์ ๋น์ทํ ์ญํ ์ ํ์ง๋ง,
๊ฐ์ฒด์ ๋ฉค๋ฒ ์ ๊ทผ์ด ์๋ ๋ฐฐ์ด๊ณผ ๊ฐ์ ์ปฌ๋ ์ ๊ฐ์ฒด์ ์ฒจ์๋ฅผ ์ด์ฉํ ์ฐธ์กฐ์ ์ฌ์ฉ๋๋ค๋ ์ ์ด ๋ค๋ฅด๋ค.
์์ค์ฝ๋
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)
{
ArrayList a = null;
a?.Add("์ผ๊ตฌ"); //a?.๊ฐ null์ ๋ฐํํ๋ฏ๋ก Add() ๋ฉ์๋๋ ํธ์ถ๋์ง ์์
a?.Add("์ถ๊ตฌ");
WriteLine($"Count : {a?.Count}");//a?.๊ฐ null์ ๋ฐํํ๋ฏ๋ก "Count:"์ธ์๋ ์๋ฌด ๊ฒ๋ ์ถ๋ ฅํ์ง ์๋๋ค.
WriteLine($"{a?[0]}"); //์๋ฌด๊ฒ๋ ์ถ๋ ฅํ์ง ์์
WriteLine($"{a?[1]}"); //์๋ฌด๊ฒ๋ ์ถ๋ ฅํ์ง ์์
a = new ArrayList(); //์ด์ ๋์ด์ null์ด ์๋๋ค.
a?.Add("์ผ๊ตฌ");
a?.Add("์ถ๊ตฌ");
WriteLine($"Count : {a?.Count}");//2
WriteLine($"{a?[0]}"); //์ผ๊ตฌ
WriteLine($"{a?[1]}"); //์ถ๊ตฌ
}
}
}
์ถ๋ ฅ๊ฒฐ๊ณผ
Count :
Count : 2
์ผ๊ตฌ
์ถ๊ตฌ
728x90