Null-propagation replacement for null check prior

2019-07-09 13:05发布

After seeing a similar question, I was wondering if the following expression ...

if (attribute != null && attribute.Description == input)

... would behave (almost) identical, to following null-propagation variant?

if (attribute?.Description == input)

So far, I could determine only following (somehow minor) differences:

  • not possible in case input is of non-nullable type
  • in case input would be itself null, behavior would be altered

Am I missing something? or are there other differences in behavior?


EDIT: in the end, the only fail-safe alternative I've found for the first snippet, would be:

if (attribute?.Description?.Equals(input) ?? false)

1条回答
啃猪蹄的小仙女
2楼-- · 2019-07-09 13:22

The code will work if input is of a non-nullable type. There is an implicit conversion of all non-nullable types to their nullable counterparts, so input will simply be lifted to a nullable to be compared to the property value.

The only difference in behavior, as you mentioned is that, if input is null, then the second snippet has no way of differentiating between attribute being null, when it should be false, and where Description is null, where it should be true.

Oh, and this is assuming that attribute is a local variable or field. If it's a property (or is actually a more complex expression) then it could have side effects or result in a different value when computed twice, as happens in the first snippet but not the second, which is a difference in behavior.

This is all of course assuming a single threaded context. In a multithreaded context, if attribute is accessible from another thread (either because it's a field that's accessible or because it's closed over in a lambda that is exposed to another thread) then the value could be different each time it's computed, so the two snippets differ for the same reason described in the previous paragraph.

查看更多
登录 后发表回答