Replacing null propagation to validate null validation before conditional expression

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

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

... will behave (almost) identical to the next version of zero propagation?

 if (attribute?.Description == input) 

Until now, I could only determine the following (somehow minor) differences:

  • impossible if input has type with zero value
  • in case input is null itself, the behavior will be changed

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




EDIT: The only failsafe alternative I found for the first snippet would be:

 if (attribute?.Description?.Equals(input) ?? false) 
+1
null c # language-features null-propagation-operator
Dec 05 '16 at 2:48
source share
1 answer

Code will work if input is of type not containing NULL. There is an implicit conversion of all non-empty types to their nullable copies, so input will simply be canceled to NULL to compare with the property value.

The only difference in behavior, as you already mentioned, is that if input is null , then the second fragment cannot distinguish attribute null when it should be false , and where Description is null , where it should be true .

Oh, and that assumes attribute is a local variable or field. If this property (or actually a more complex expression), then it can have side effects or lead to a different value when calculated twice, as it happens in the first fragment, but not in the second, which is the difference in behavior.

This, of course, assumes a single-threaded context. In a multi-threaded context, if an attribute is accessible from another thread (either because it is available, or because it is closed in a lambda that undergoes another thread), then the value may be different each time it is evaluated, so there are two fragments differ for the same reason as in the previous paragraph.

+3
Dec 05 '16 at 2:52
source share



All Articles