Question
I’d like to have a class that is able to handle a null reference of itself. How can I do this? Extension methods are the only way I can think to do this but thought I’d ask in case there was some nifty thing I didn’t know about C#.
Example
I have a class called User with a property called IsAuthorized.
When User is properly instantiated IsAuthorized has an implementation. However, when my User reference contains null I’d like a call to IsAuthorized to return false instead of exploding.
Solution
Lot’s of good answers. I ended up using three of them to solve my problem.
- I used the Null Object design pattern suggested by Zaid Masud.
- I combined that with Belmiris’ suggestion of using struct so I couldn’t have a null reference
- And got a great explanation for why C# works this way and how I could really solve it from Jon Hanna
Unfortunately I can only pick one of these as my accepted answer so if you are visiting this page you should take the time to up vote all three of these and any of the other excellent answers that were given.
How about a proper Object Oriented solution? This is exactly what the Null Object design pattern is for.
You could extract an IUser interface, have your User object implement this interface, and then create a NullUser object (that also implements IUser) and always returns false on the IsAuthorized property.
Now, modify the consuming code to depend on IUser rather than User. The client code will no longer need a null check.
Code sample below:
Now, your code will return an IUser rather than a User and client code will only depend on IUser: