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

前端 未结 7 1143
青春惊慌失措
青春惊慌失措 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:29

    If the variable is null, it means it references no object, therefore is makes no sense (and I think its not technically possible) to handle the null reference inside the class method.

    You should guarantee that it is not null, either by checking just before calling "IsAuthorized" or event before.

    Edit: Finding an workaround to do that would be a bad thing: it would be confusing for someone to understand the behavior, since it is not the "expected" behavior for the programming language. It could also cause your code to hide some problem (a null value where it should be an object) and create a bug that will be hard to find. That said: it is for sure a bad idea.

提交回复
热议问题