I don't like this… Is this cheating the language?

前端 未结 15 2659
一向
一向 2021-02-13 15:52

I have seen something like the following a couple times... and I hate it. Is this basically \'cheating\' the language? Or.. would you consider this to be \'ok\' because the IsNu

相关标签:
15条回答
  • 2021-02-13 16:26

    Theres nothing wrong with this.

    if(conditions are evaluated from left to right so it's perfectly fine to stack them like this.

    0 讨论(0)
  • 2021-02-13 16:28

    It makes sense because C# by default short circuits the conditions, so I think it's fine to use that to your advantage. In VB there may be some issues if the developer uses AND instead of ANDALSO.

    0 讨论(0)
  • 2021-02-13 16:28

    I don't think it's any different than something like this:

    INT* pNumber = GetAddressOfNumber();
    
    if ((pNUmber != NULL) && (*pNumber > 0))
    {
      // valid number, do whatever
    }
    else
    {
      // On a null pointer, it drops to here, because (pNumber != NULL) fails
      // However, (*pNumber > 0), if used by itself, would throw and exception when dereferencing NULL
    }
    

    It's just taking advantage of a feature in the language. This kind of idiom has been in common use, I think, since C started executing Boolean expressions in this manner (or whatever language did it first).)

    0 讨论(0)
  • 2021-02-13 16:30

    This is perfectly valid and there is nothing wrong with using it that way. If you are following documented behaviour for the language than all is well. In C# the syntax you are using are the conditional logic operators and thier docemented bahviour can be found on MSDN

    For me it's the same as when you do not use parenthesis for when doing multiplication and addition in the same statement because the language documents that the multiplication operations will get carried out first.

    0 讨论(0)
  • 2021-02-13 16:32

    There is nothing wrong with this, as you just want to make certain you won't get a nullpointer exception.

    I think it is reasonable to do.

    With Extensions you can make it cleaner, but the basic concept would still be valid.

    0 讨论(0)
  • 2021-02-13 16:32

    This code is totally valid, but I like to use the Null Coalesce Operator for avoid null type checks.

    string someString = MagicFunction() ?? string.Empty;
    if (someString.Length > 3)
    {
        // normal string, do whatever
    }
    else
    {
       // NULL strings will be converted to Length = 0 and will end up here.
    }
    
    0 讨论(0)
提交回复
热议问题