How the zero-carbon operator works

I got three classes (classA, classB and classC) that inherit from the IFoo interface; if you use this

var fooItem = (request.classAitem ?? (request.classBitem as IFoo ?? request.classCitem)) 

or

 var fooItem = (request.classAitem ?? request.classBitem ?? request.classCitem as IFoo) 

it works fine, but other combinations don't even compile:

 var fooItem = (request.classAitem as IFoo ?? request.classBitem ?? request.classCitem) 

or

 var fooItem = (request.classAitem ?? request.classBitem ?? request.classCitem) as IFoo 

It seems to me that in some cases, the compiler implicitly decompresses the child classes into its IFoo interface, but in some other cases they do not. What do you guys think?

+6
source share
1 answer

In both examples that do not work since ?? is right-associative, we first try to determine the data type of this expression:

 request.classBitem ?? request.classCitem 

A data type can only be a data type of one of its inputs if the data types are different. There obviously are no conversions in any direction, so you get a compiler error. Note that the compiler will not decide that the data type is IFoo here just because both classes implement it (and if this happened, what would happen if they both implemented several common interfaces?)

Compare this to your two two examples. In the first case, we will first consider this expression:

 request.classBitem as IFoo ?? request.classCitem 

The type of this expression is either IFoo or any request.classCitem data type. There, the conversion is performed from the type request.classCitem to IFoo and so that it is obviously selected, and therefore the entire data type of the expression is IFoo . It is then used to determine the type of general expression (again, IFoo ).

The second case is very similar, as ?? is associative right 1 we must first determine the type:

 request.classBitem ?? request.classCitem as IFoo 

And again, we have a choice between IFoo and any request.classBitem data type. There, the conversion to IFoo selected.

1 And also note that this means that the brackets in the first example are redundant.

+5
source

All Articles