Null Value
Explore how to handle null values effectively in C# by managing nullable reference and value types. Learn to use null checks, the null-coalescing operator, and the null-conditional operator to prevent runtime errors and write safer code.
In C#, we have a special value called null. This value represents the absence of a value. Understanding how to manage this state is essential for writing robust and error-free applications.
The null and reference types
In modern C#, reference types are non-nullable by default. We must explicitly indicate if a variable can hold a null value by adding a ? to the type. This syntax mimics how we handle nullable value types.
string? name = null;
We declare a variable name of type string?. The ? indicates that this reference type can accept null. We assign null to it, meaning it currently points to nothing in memory.
Assigning null to a non-nullable type, such as string, triggers a compiler warning to help prevent runtime errors.
If we try to access a member (like a method or property) of a variable that is currently null, the runtime throws a NullReferenceException.
Line 1: We initialize
nameasnull.Line 4: We attempt to call the
.ToUpper()method onname. Sincenameis null, the runtime throws aNullReferenceException. ...