Tip
이 문서는 하나 이상의 프로그래밍 언어를 알고 C#을 학습하는 개발자를 위한 기본 사항 섹션의 일부입니다. 프로그래밍을 처음 접하는 경우 먼저 시작 자습서로 시작 하세요. 자세한 내용은 언어 참조의 Nullable 값 형식 을 참조하세요.
nullable 값 형식은 기본 값 형식 T?T의 모든 값과 추가 null 값을 나타냅니다. 형식 int? 의 변수는 정수나 null "값 없음"을 나타냅니다.
값 형식(예: int, bool, 및 DateTime)은 기본적으로 null을(를) 보유할 수 없습니다. 이 동작은 효율적이며 많은 오류를 방지합니다. 그러나 이 제한으로 인해 값이 진정으로 없을 수 있는 경우 문제가 발생합니다. 일반적인 시나리오는 데이터베이스에서 읽는 것입니다. 정수 열에 숫자가 포함되거나 SQL에서 값이 전혀NULL 포함되지 않을 수 있습니다. 간단한 int는 그 부재를 나타낼 수 없지만, int?는 가능합니다.
nullable 값 형식 선언
모든 값 형식에 ?를 추가하여 Null을 허용할 수 있게 만듭니다.
int? age = null; // integer with no value yet
double? price = 9.99; // nullable double with a value
bool? isActive = null; // boolean with no value
age = 30; // assign a value later
int?[] scores = [100, null, 85, null, 72]; // array with absent entries
nullable 값 형식의 기본값은 null기본 형식의 기본값이 아닌 값입니다.
값이 있는지 확인
nullable 값 형식을 확인하고 해당 값을 추출하는 권장 방법은 형식 패턴을 사용하는 것입니다.
int? temperature = 72;
if (temperature is int degrees)
{
Console.WriteLine($"Temperature is {degrees}°F.");
}
else
{
Console.WriteLine("Temperature is not recorded.");
}
// Output: Temperature is 72°F.
패턴은 is int degrees이 null이 아닌 경우에만 일치하며, 동시에 값을 temperature에 바인딩합니다. 한 단계에서 null 검사와 값 추출을 모두 가져옵니다.
또는 HasValue 및 Value 속성을 사용합니다.
int? count = 42;
if (count.HasValue)
{
Console.WriteLine($"Count is {count.Value}.");
}
else
{
Console.WriteLine("Count has no value.");
}
// Output: Count is 42.
새 코드의 is T value 패턴을 선호합니다. 일치하는 분기 내에서 범위가 지정된 null이 될 수 없는 새 변수를 도입하여 의도를 더 명확히 하고, null 검사 외부에서 실수로 Value를 사용하려는 유혹을 제거합니다. 그렇지 않으면 InvalidOperationException 예외가 발생합니다.
다음과 직접 비교할 수도 있습니다.null
int? quantity = null;
if (quantity != null)
{
Console.WriteLine($"Quantity: {quantity.Value}");
}
else
{
Console.WriteLine("Quantity is not set.");
}
// Output: Quantity is not set.
대체를 사용하여 값 가져오기
nullable에서 null을 허용하지 않는 값이 필요한 경우 GetValueOrDefault 또는 null 병합 연산자 ??를 사용합니다.
int? rating = null;
int result1 = rating.GetValueOrDefault(); // 0 (default for int)
int result2 = rating.GetValueOrDefault(-1); // -1 (specified fallback)
Console.WriteLine(result1); // 0
Console.WriteLine(result2); // -1
rating = 5;
int result3 = rating.GetValueOrDefault(-1); // 5 (actual value)
Console.WriteLine(result3); // 5
연산자 ??는 종종 인라인으로 사용하는 것이 더 효율적입니다.
int? priority = null;
int effective = priority ?? 0; // 0 because priority is null
Console.WriteLine(effective); // 0
priority = 3;
effective = priority ?? 0; // 3 because priority has a value
Console.WriteLine(effective); // 3
두 방법 모두 실제 값이 있으면 반환하고, 그렇지 않을 때 지정한 대체(fallback)를 반환합니다.
nullable 값 형식을 사용하는 산술 연산
nullable 값 형식의 산술 연산자 및 비교 연산자가 승격됩니다. 피연산자 중 하나가 null인 경우 결과는 오류가 아닌 null입니다.
int? a = 10;
int? b = 20;
int? c = null;
int? sum = a + b; // both non-null: result is 30
int? product = a * c; // one operand is null: result is null
Console.WriteLine(sum); // 30
Console.WriteLine(product.HasValue); // False — null propagates through arithmetic
Null은 기본적으로 산술 연산을 통해 전파됩니다. null 결과가 추가적인 문제를 일으키지 않도록 하려면 계산에 사용하기 전에 ?? 값 또는 GetValueOrDefault 값을 추출합니다.
참고하십시오
.NET