How useful is C#'s ?? operator?

后端 未结 13 2115
独厮守ぢ
独厮守ぢ 2020-12-08 07:43

So I have been intrigued by the ?? operator, but have still been unable to use it. I usually think about it when I am doing something like:

var x = (someObje         


        
13条回答
  •  Happy的楠姐
    2020-12-08 08:24

    It often seems to be a nice idea to replace a verbose bit of syntax with a more compact form. But usually it ends up just obfuscating the code without really gaining anything. Modern standards advocate longer and more descriptive variable names and use of more verbose layout styles in order to make code more readable & more maintainable.

    If I'm going to train my brain to quickly parse ??, I need to find a situation where it shows a clear advantage - something that can't be done another way, or somewhere that it saves a significant amount of typing.

    And this is where ?? falls down for me. It is useful so infrequently and ?: and if/else are such quick and readable alternatives that there really seems little point in using a different syntax that achieves nothing new.

    a = b ?? c ?? d ?? e; sounds great. But I've never needed to do that!

    What I find irritating is that I want to use ??, but every single time I think "ooh, maybe I can use ?? here", I realise that I don't want to use the object itself, but a member of it.

    name = (user == null) ? "doe" : user.Surname;

    And unfortunately, ?? doesn't help here.

提交回复
热议问题