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
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#.