번역/C# Notes for Professionals
38.4: 기본 값을 지정하여 Nullable 타입이 가지고 있는 값 가져오기
노초코
2022. 1. 26. 22:56
Section 38.4: 기본 값을 지정하여 Nullable 타입이 가지고 있는 값 가져오기
GetValueOrDefault()
메소드를 이용하면 HasValue
속성이 false
인 경우에도 값을 반환받을 수 있다 (Value
속성값 접근은 이러한 경우 예외를 발생시킨다는 차이점이 있다).
class Program {
static void Main() {
int ? nullableExample = null;
int result = nullableExample.GetValueOrDefault();
Console.WriteLine(result); // int 에 대한 기본값인 0 을 출력할 것이다
int secondResult = nullableExample.GetValueOrDefault(1);
Console.WriteLine(secondResult); // 기술된 기본값인 1 을 출력할 것이다
int thirdResult = nullableExample ?? 1;
Console.WriteLine(thirdResult); // GetValueOrDefault 와 동일하지만 조금 더 간결하다
}
}
출력결과:
0
1
1
본 문서는 C# Notes for Professionals (라이센스:CC-BY-SA) 를 한글로 번역한 문서입니다. 번역상 오류가 있을 수 있으므로 정확한 내용은 원본 문서를 참고하세요.
[출처] https://books.goalkicker.com/CSharpBook/
반응형