Machineboy空
C# Nullablity , Null 체크, NullReferenceException 본문
Null
absence of a value.
C# 8.0 이전
// 참조 타입: null 가능
string nullableReferenceType = "hello";
nullableReferenceType = null;
// 값 타입 : null이 될 수 있음을 명시해줘야 했다.
int nonNullableValueType = 5;
nonNullableValueType = null; // compile error: not nullable
int? nullableValueType = 5;
nullableValueType = null;
// null값에 접근하려고 하면 NullReferenceException 에러
string sentence = null;
sentence.Lenth; // NullReferenceException
C# 8.0 이후
// non-nullable을 default로
string nonNullableReferenceType = "book";
nonNullableReferenceType = null; // compile warning
string? nullableReferenceType = "movie";
nullableReferenceType = null;
Safely work with nullable value
// 접근 하기 전에 null인지 체크
string NormalizedName(string? name)
{
if (name == null)
{
return "UNKNOWN";
}
return name.ToUpper();
}
NormalizedName(null); // "UNKNOWN"
NormalizedName("Elisabeth");// "ELISABETH"
// ?? 사용
string? name1 = "John";
name1 ?? "Paul"; // "John"
string? name2 = null;
name2 ?? "George";
// ?. 사용
string? fruit = "apple";
fruit?.Length; // 5
string? vegetable = null;
vegetable?.Length; //null