프로그래밍/C#

[C#] Nullable<T>

갓똥 2020. 2. 4. 17:30
728x90
반응형

1. 핵심 정리

using System;

class Program {
    public static void Main() {
        // string : reference type
        string s1 = "Hello"; // 객체 생성
        string s2 = null;    // 객체 없음.
        
        // int : value type
        int n1 = 10;  // 객체 생성
        int n2 = ?;   // 값이 없음을 표현하고 싶을 땐?
    }
}

 ① Reference Type

    => null을 사용하면 객체 없음 상태를 표현할 수 있다.

 

 ② Value Type

    => 값 없음을 표현할 수 없다.

 

 ③ Nullable<T>

    => Value Type에 값 없음을 추가한 것

    => Nullable<int> = int + bool

    => null을 사용할 수 있다.

 

using System;

class Program {
    public static void Main() {
        // string : reference type
        string s1 = "Hello"; // 객체 생성
        string s2 = null;    // 객체 없음.
        
        // int : value type
        Nullable<int> n1 = 10;
        Nullable<int> n2 = null;
        
        if(n2 == null) { }
    }
}

 

 

언제 쓰면 될까?
예를 들어, int타입의 함수를 만들고 어떠한 처리를 하는데 실패할경우 -1을 리턴하는 함수가 있다고 해보자.
-1이 리턴 됐을 때 정상 처리로 -1이 나온 것인지 실패로 인한 -1인지 헷갈릴 수 있다.
이런경우 Nullable<int>타입의 함수로 만들어 실패 시 null을 리턴할 수 있다.
using System;

class Program {
    public static int t1() {
        if(실패)
            return -1;
    }
    
    public static Nullable<int> t2() {
        if(실패)
            return null;
    }

    public static void Main() {
        int? n = null; // Nullable<int> n = null;
    }
}

 ④ int?

    => Nullable<int>의 단축 표기법

 


2. 추가 정리

using System;

class Program {
    public static void Main() {
        int? n1 = 10;
        int  a1 = 20;
        
        n1 = a1; // int? = int - ok
        a1 = n1; // int = int? - error
        
        Console.WriteLine(a1);
    }
}

위의 그림과 같이 Nullable<int>는 값의 int와 값이 있는지의 bool이 합쳐진 형태이다.
그래서 n1 = a1;은 a1이 가지고 있는 모든정보를 n1에 담을 수 있으므로 문제가 없지만
n1이 가지고 있는 bool의 정보를 a1이 가질 수 없으므로 에러가 난다.
아래와 같이 명시적으로 해결을 할 순 있다.
using System;

class Program {
    public static void Main() {
        int? n1 = 10;
        int  a1 = 20;
        
        n1 = a1; // int? = int - ok
        // a1 = n1; // int = int? - error
        
        a1 = (int)n1;
        
        Console.WriteLine(a1);
    }
}

 

하지만 위와 같은 경우는 n1에 초기값으로 null을 넣을 경우 예외가 발생한다.
추가로, Nullable도 연산은 모두 가능하지만 한쪽이 null일 경우 계산 결과도 null이 된다는 점 주의.
728x90
반응형