Short circuiting statement evaluation — is this guaranteed? [C#]

后端 未结 6 2261
不思量自难忘°
不思量自难忘° 2020-12-10 11:53

Quick question here about short-circuiting statements in C#. With an if statement like this:

if (MyObject.MyArray.Count == 0 || MyObject.MyArray[0].SomeValu         


        
6条回答
  •  温柔的废话
    2020-12-10 12:54

    Just a small observation.

    You said this:

    Otherwise I'll get a null exception in the second part. (emphases mine)

    This isn't true, actually. If short-circuiting weren't guaranteed, you could get an IndexOutOfRangeException in the second part.

    It's still possible you could get a NullReferenceException, if the first item in your MyArray object is actually null (or if any of the other objects in that expression are).

    The only totally safe check would be this:

    bool conditionHolds =
        MyObject == null ||
        MyObject.MyArray == null ||
        MyObject.MyArray.Count == 0 ||
        MyObject.MyArray[0] == null ||
        MyObject.MyArray[0].SomeValue == 0;
    
    if (conditionHolds)
    {
        //....
    }
    

提交回复
热议问题