Zero Propagation Operator

I looked around a bit, but could not find an answer to how the new C # 6.0 compiler breaks a new NULL distribution command for something like the following:

BaseType myObj = new DerivedType(); string myString = (myObj as DerivedType)?.DerivedSpecificProperty; 

I want to know exactly how he handles this.

Does it as cast to a new DerivedType variable (i.e. it's just syntactic sugar for casting as followed by a null comparison).

Or, if it is actually as , do it, check the value is null, and then, if not null, convert and continue moving.

+6
source share
1 answer

Does cache as new DerivedType variable (i.e. it's just syntactic sugar for casting as followed by a null comparison).

Yes.

Your code will compile something like this:

 BaseType myObj = new DerivedType(); DerivedType temp = myObj as DerivedType; string myString = temp != null ? temp.DerivedSpecificProperty : null; 

You can see this with this TryRoslyn example (although, as hvd commented by looking at IL, you can see that there is actually no DerivedType variable. The link is simply stored on the stack).

+8
source

All Articles