< Nullable > : λΉμ΄ μλ μνκ° λ μ μλ νμ
Null(λΉμ΄μλ) + able(~λ μ μλ) = "λΉμ΄ μλ μνκ° λ μ μλ"
using System;
using System.Text;
using static System.Console;
namespace Hello
{
class MainApp
{
static void Main(string[] args)
{
int? a = null;
int? b = null;
int? c = null;
//int d = null; μ»΄νμΌ μ€λ₯!
}
}
}
νλ‘κ·Έλλ°μ νλ€ λ³΄λ©΄ μ΄λ€ κ°λ κ°μ§μ§ μλ λ³μκ° νμν λκ° μλ€.
0μ΄ μλ λΉμ΄μλ λ³μ,
μ¦ null μνμΈ λ³μλ₯Ό μνλ€λ©΄
λ³μμκ² ν λΉλ λ©λͺ¨λ¦¬ 곡κ°μ λΉμλ μ μλλ‘ Nullable νμμ μ¬μ©νλ©΄ λλ€.(κ° νμμ ννμ¬)
Nullable νμμ λ³μλ₯Ό μ μΈν λλ μλμ λ°μ΄ν° νμ μ΄λ¦ λ€μ '?'λ§ λΆμ¬μ£Όλ©΄ λλ€.
λ°μ΄ν°νμ ? λ³μμ΄λ¦;
int d = null;κ° μ»΄νμΌ μ€λ₯κ° λλ μ΄μ λ
int νμμ λΉμλ μ μκ³ (null κ°μ κ°μ§ μ μλ) λ°μ΄ν° νμμ΄κΈ° λλ¬Έμ΄λ€.
< HasValue, Value >
λͺ¨λ Nullable νμμ HasValueμ Value λ κ°μ§ μμ±μ κ°κ³ μλ€. (intλ μ»΄νμΌ μλ¬!)
HasValue μμ±μ ν΄λΉ λ³μκ° κ°μ κ°κ³ μλμ§ λλ κ·Έλ μ§ μμμ§λ₯Ό λνλ΄κ³ ,
Vlaue μμ±μ λ³μμ λ΄κ²¨ μλ κ°μ 보μ¬μ€λ€.
using System;
using System.Text;
using static System.Console;
namespace Hello
{
class MainApp
{
static void Main(string[] args)
{
int? a = null;
int? b = 10;
WriteLine(a.HasValue); //False
WriteLine(b.HasValue); //True
WriteLine(b.Value); //10
a = 8;
WriteLine(a.HasValue); //True
WriteLine(a.Value); //8
}
}
}
λΉμ μμ μΈ μ κ·Ό μλ: μ΄λ€ Nullable νμ λ³μμ HasValue μμ±μ΄ False κ°μ κ°κ³ μλ€λ©΄
κ·Έ λ³μλ λΉμ΄ μλ€λ λ»μ΄λ€.
μ΄ λ³μμ λν΄ Value μμ±μ μ΄μ©νμ¬ κ°μ κΊΌλ΄λ € μλνλ©΄
CLRμ InvaildOperation Exception μμΈλ₯Ό λμΈ κ²μ΄λ€.
using System;
using System.Text;
using static System.Console;
namespace Hello
{
class MainApp
{
static void Main(string[] args)
{
int? a = null;
WriteLine(a.HasValue); //False
WriteLine(a.Value);
}
}
}
μΆλ ₯
False
μ²λ¦¬λμ§ μμ μμΈ: System.InvalidOperationException: Null νμ© κ°μ²΄μλ κ°μ΄ μμ΄μΌ ν©λλ€.
μμΉ: System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
μμΉ: System.Nullable`1.get_Value()
λ°λΌμ Nullable νμμ μ¬μ©ν λλ HasValue μμ±μ νμΈνκ±°λ nullκ³Ό κ°μμ§λ₯Ό λΉκ΅νμ¬
λ³μκ° λΉμ΄ μλμ§ νμΈνλ μ¬μ κ²μ¬κ° νμνλ€.
'C# > μ΄κ²μ΄ C#μ΄λ€' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
9. κ³΅μ© νμ μμ€ν (0) | 2022.02.07 |
---|---|
8. Var, Object νμκ³Όμ μ°¨μ΄? (0) | 2022.02.07 |
6. μμμ μ΄κ±° νμ (const, enum): νλ‘κ·Έλλ¨Έμ μ€μλ₯Ό λ§λ μ₯μΉ (0) | 2022.02.07 |
5. Parseμ ToString() λ¬Έμμ΄μ μ«μλ‘, μ«μλ₯Ό λ¬Έμμ΄λ‘ (0) | 2022.02.07 |
4. object νμ, λ°μ±κ³Ό μΈλ°μ± (0) | 2022.02.07 |