Checking and Preventing Null
Learn two strategies to prevent a NullReferenceException.
We'll cover the following
We shouldn’t wrap a try
/catch
block around a code snippet to fix a NullReferenceException
. Instead, we should check for null
and defend against it. That’s the solution to the NullReferenceException
.
We have learned that we get a NullReferenceException
whenever we access a property or method of a null
reference. We have covered two scenarios: using null
as the returned value from a method and passing null
as a parameter to methods. Let’s start by checking the returned value from methods to avoid a NullReferenceException
.
Checking for null
Let’s revisit our example with movies to add a null
check and prevent a NullReferenceException
.
Get hands-on with 1400+ tech skills courses.