๋ณธ๋ฌธ์œผ๋กœ ๋ฐ”๋กœ๊ฐ€๊ธฐ

[C#] Nullable

category ๐Ÿ—ฏ๏ธLanguage/C# 2022. 3. 9. 15:31
728x90

 

 

C#์—์„œ ๊ฐ’ ํ˜•์‹(value type)์— ํ•ด๋‹นํ•˜๋Š” ์ž๋ฃŒํ˜•๋“ค์ด ์žˆ๋‹ค. (byte, int, float, ...)

์ด๋Ÿฐ ๊ฐ’ ํ˜•์‹์˜ ๋ณ€์ˆ˜๋“ค์€ ์ดˆ๊ธฐํ™”ํ•ด์„œ ์‚ฌ์šฉํ•˜์ง€ ์•Š์œผ๋ฉด C# ์ปดํŒŒ์ผ๋Ÿฌ๋Š” ์ปดํŒŒ์ผ์กฐ์ฐจ ํ•ด์ฃผ์ง€ ์•Š๋Š”๋‹ค.

 

ํ•˜์ง€๋งŒ, ๊ฐœ๋ฐœ์„ ํ•˜๋‹ค ๋ณด๋ฉด ์ด๋Ÿฐ ๊ฐ’ ํ˜•์‹์˜ ๋ฐ์ดํ„ฐ์—๋„ ์–ด๋– ํ•œ ๊ฐ’๋„ ๊ฐ€์ง€์ง€ ์•Š๊ฒŒ ํ•˜๊ณ  ์‹ถ์€ ๊ฒฝ์šฐ๊ฐ€ ์ข…์ข… ์žˆ๋‹ค.

์ฐธ์กฐ ํ˜•์‹(reference type)์€ null์„ ์ค„ ์ˆ˜ ์žˆ์ง€๋งŒ, ๊ฐ’ ํ˜•์‹์—๋Š” null์„ ์ค„ ์ˆ˜๊ฐ€ ์—†๋‹ค.

๊ทธ๋ž˜์„œ, C#์—์„œ๋Š” ์ด๋Ÿฐ ๊ฐ’ ํ˜•์‹ ์ž๋ฃŒํ˜• ๋ณ€์ˆ˜์—๋„ null ๊ฐ’์„ ํ• ๋‹นํ•  ์ˆ˜ ์žˆ๋„๋ก Nullable ํ˜•์‹์ด๋ž€ ๊ฑธ ์ง€์›ํ•œ๋‹ค.

 

 

Nullable

 

๊ฐ’ ํ˜•์‹์— ํ•œํ•ด์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ์„ ์–ธํ•˜๋Š” ๋ฐฉ์‹์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

๋ฐ์ดํ„ฐํƒ€์ž…? ๋ณ€์ˆ˜์ด๋ฆ„;

 

์‚ฌ์šฉ ์˜ˆ์‹œ๋ฅผ ๋ณด๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์“ธ ์ˆ˜ ์žˆ๋‹ค.

// int data = null;    ์˜ค๋ฅ˜
int? data = null;

 

 

hasValue์™€ Value ์†์„ฑ

 

๋ชจ๋“  Nullable ํ˜•์‹์€ hasValue์™€ Value ์†์„ฑ์„ ๊ฐ€์ง„๋‹ค.

int? data = null;
Console.WriteLine(data.HasValue);   // data๋Š” null์ด๋ฏ€๋กœ False  ์ถœ๋ ฅ

int a = 100;
Console.WriteLine(a.HasValue);      // a = 100 ์ด๋ฏ€๋กœ True ์ถœ๋ ฅ
Console.WriteLine(a.Value);         // 100 ์ถœ๋ ฅ

 

 

๋งŒ์•ฝ HasValue = False์ธ๋ฐ Value๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค๋ฉด, CLR์€ InvalidOperationException ์˜ˆ์™ธ๋ฅผ ๋„์šด๋‹ค.

 

 

728x90
๋ฐ˜์‘ํ˜•