지니워의 일상다반사
Nullable 형식 본문
1. Nullable형식이란?
- 0이 아닌 비어 잇는 변수, 즉 null 상태인 변수를 쓰고 싶을 때 사용
- 비어 있는 상태가 될 수 있는 형식
[데이터형식? 변수이름;] 으로 사용 가능
ex) int? a = null;
double? b = null;
2. HasValue와 Value 속성
- HasValue 속성은 해당 변수가 갑을 갖고 있는지 또는 그렇지 않는지를 나타냄
- Value 속성은 변수에 담겨 있는 값을 나타 냄
ex)
int? a = null;
Console.WriteLine(a.HasValue); // a는 null이므로 False를 출력
a = 10;
Console.WriteLine(a.HasValue); // a는 10을 갖고 있으므로 True 출력
Console.WriteLine(a.Value); // 10을 출력
[예제코드]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Nullable { class MainApp { static void Main(string[] args) { int? a = null; Console.WriteLine(a.HasValue); Console.WriteLine(a != null); a = 3; Console.WriteLine(a.HasValue); Console.WriteLine(a != null); Console.WriteLine(a.Value); } } } | cs |
Comments