Exercise: Refactoring a Function to Prevent Null
Refactor a function to fix a NullReferenceException.
We'll cover the following
Preventing a NullReferenceException
Now, let’s play!
Let’s refactor a method that throws a NullReferenceException
. For this exercise, we’ll continue working with a catalog of movies. This time, each movie contains a director and some reviews. Each review has a score and a comment.
When working with collections, we can prevent a NullReferenceException
by always initializing collections before using them. For example, before trying to add an element to a list, we should initialize it to an empty list.
To complete this exercise, add null
checks, initialize collections, and use ArgumentNullException
where appropriate to prevent a NullReferenceException
.
Follow the instructions in the comments to complete this exercise.
Get hands-on with 1400+ tech skills courses.