Is there a way to have a C# class handle its own null reference exceptions

前端 未结 7 1144
青春惊慌失措
青春惊慌失措 2021-02-05 05:05

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

7条回答
  •  逝去的感伤
    2021-02-05 05:30

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

提交回复
热议问题