Null Object Pattern in C#

| By Webner

The null object pattern is designed to handle the null exception of objects without implementing too many null checks in the application. This is done by identifying the behaviour that should occur when a null is encountered and declaring a default object for that instance that should be passed when a null object is encountered.
For instance, consider a shopping website that looks up users based on their user id:
C Sharp
Now imagine that elsewhere the application needs to display some details about the user that was found, such as their name, etc. We will need to be careful to check for null objects in the application:
When implementing a large amount of code, it’s very easy to miss a check, in which case a runtime null reference exception can occur.
To implement the Null Object Pattern, a static instance of User is created to represent the case of a “not found” user:
Then, wherever you would have a method that could return a null User, there you can return the static instance instead:
Once the Null Object Pattern is in place, there is no need to even have the local variables (UserName, UserId) shown in the example above, as they only existed because the user instance might be null. Therefore, their null checks are also not needed. Hence, client code will become simpler and will have fewer duplicated codes since these kinds of null checks are mostly present throughout the code in our applications.

Leave a Reply

Your email address will not be published. Required fields are marked *