Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null propagation operator

Tags:

c#

.net

c#-6.0

I've looked around a bit but haven't been able to find an answer to how the new C# 6.0 compiler breaks down the new null propagation command for something such as the following:

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

What I want to know is how exactly it handles this.

Does it cache the as cast into a new DerivedType variable (i.e., this is just syntactical sugar for an as cast followed by an null comparison).

Or if it actually as cast it, check for null, then if not null, recast and keep going.

like image 252
GEEF Avatar asked Jan 04 '16 22:01

GEEF


1 Answers

Does it cache the as cast into a new DerivedType variable (i.e., this is just syntactic sugar for an as cast followed by an null comparison).

Yes.

Your code will be compiled to something like this:

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

You can see that with this TryRoslyn example (though, as hvd commented, by looking at the IL you can see there isn't actually a DerivedType variable. The reference is simply stored on the stack).

like image 196
i3arnon Avatar answered Nov 03 '22 00:11

i3arnon