Introducing Nullable Value Types
Declare int?, double? and understand Nullable .
Value Types Cannot Be Null
Normally an int always holds a number; it can never be null. Sometimes you need to represent "no value", such as a missing measurement.
using System;
class Program {
static void Main() {
int count = 0;
Console.WriteLine(count);
}
}Nullable with ?
Add ? after a value type to make it nullable. int? can hold any int or null.
using System;
class Program {
static void Main() {
int? maybe = null;
Console.WriteLine(maybe.HasValue);
maybe = 42;
Console.WriteLine(maybe);
}
}All lessons in this course
- Introducing Nullable Value Types
- HasValue and Value Properties
- Null-Coalescing Operators
- Nullable in Calculations