Null Value
Explore how null values represent missing data in C#, distinguish between reference and value types, and learn to use nullable types with the ? syntax. Understand the importance of null checks and the null coalescing operator ?? to write safer and more robust code that prevents NullReferenceException errors.
We'll cover the following...
The null and reference types
In C#, we have a special value called null. This value represents the absence of value and is the default for reference-type variables.
string name = null;
The null value means that a variable doesn’t point to anything in memory. Because we’re dealing with references, we can’t assign null to a value-type variable, such as int.
If we try to access a variable that doesn’t point to anything, we get a NullReferenceException:
The null and value types
Unlike reference types, value-type variables can’t be assigned the null value directly. However, it’s quite common to potentially need a value-type to be null. For instance, if we’re fetching ...