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.
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:
public interface IUser
{
// ... other required User method/property signatures
bool IsAuthorized { get; }
}
public class User : IUser
{
// other method/property implementations
public bool IsAuthorized
{
get { // implementation logic here }
}
}
public class NullUser : IUser
{
public bool IsAuthorized
{
get { return false; }
}
}
Now, your code will return an IUser rather than a User and client code will only depend on IUser:
public IUser GetUser()
{
if (condition)
{
return new NullUser(); // never return null anymore, replace with NullUser instead
}
return new User(...);
}
However, when my User reference contains null I'd like IsAuthorized to always return false instead of exploding.
This can only be done if IsAuthorized
is a static method, in which case you can check for null. This is why extension methods can do this - they are really just a different syntax for calling a static method.
Calling a method or property, such as IsAuthorized
as an instance method requires an instance. Just the act of calling an instance method (including a property getter) on null
will trigger the exception. The exception isn't raised by your class, but by the runtime itself when you attempt to use the (null) reference. There is no way around this in C#.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With