C# Interview Question #76

What is a nullable value type in C#?

Memory Management & Modern C# Mid-Level Intermediate

Quick Interview Answer

Normal value types such as int, bool, and DateTime cannot represent null. Nullable<T>, commonly written with the ? syntax, allows a value type to contain either a normal value or null.

Detailed Explanation

Normal value types such as int, bool, and DateTime cannot represent null. Nullable<T>, commonly written with the ? syntax, allows a value type to contain either a normal value or null.

Nullable value types are useful when a value is optional, unknown, or absent, such as an optional database column.

Members such as HasValue, Value, GetValueOrDefault, and the null-coalescing operator can be used with nullable values.

Code Example

int? age = null;

if (age.HasValue)
{
    Console.WriteLine(age.Value);
}

int finalAge = age ?? 0;