开发者

Could this `if` statement generate a Null-Reference Exception ever?

开发者 https://www.devze.com 2023-02-13 09:31 出处:网络
I think my point is clear, under any condition, could this throw null-reference exception? i.e. objecting that e.Result is null while trying to access its Count property.

I think my point is clear, under any condition, could this throw null-reference exception? i.e. objecting that e.Result is null while trying to access its Count property.

if (e.Result == null || e.Result.Count == 0)
    return;

EDIT: To gain the most of this question (for later-coming askers), how will 开发者_开发问答we prevent that exception from happening, can we use lock statement? how?


That code can throw a NullReferenceException only if the method is not thread safe. Meaning, if another thread decides to assign null to e.Result at coincidentally the exact moment after your e.Result == null check and right before your e.Result.Count == 0 check.


It will only do so if e is null.


e == null

OR

Multithreading & race condition ?


It might throw "Null-Reference Exception" if Result has its own code behind it and that code is failing with that error.


No. - e.Result ==null will be evaluated first, if it is true then return will be called immediately and the second case will not be evaluated. It may be have differently in threading


            EventArgs args = e;
            if (args.Result == null || args.Result.Count == 0)
            {
                return;
            }

The idea is that you first copy the event args ( e ) into your own local element and use this for the if conditional check. Be careful to ensure that the copy is deep enough to copy the Result also ( otherwise you still end up running into the multithreading case when another thread has just nulled the result midway through the if check ). A local copy is always threadsafe.


Aside from the multithreading/race-condition issue that others have already pointed out, the topic you might be looking for is short-circuit evaluation. In C#, the || operator uses short-circuiting (as opposed to |, which is eager), so if e.Result == null evaluates to true, the e.Result.Count == 0 won't be evaluated.

Others have answered already but I wanted to give you the name for this type of behavior and some further reading.

0

精彩评论

暂无评论...
验证码 换一张
取 消