Evil Code #009 : nameof Operator

The nameof() operator has been so commonly used by the developers that one could not be called guilty if he assumes it was there since C# was born. Despite that, there are days it might still surprise you.

What would be your reply if I asked you to predict the output of the following.

nameof(School.Division.Student)

No prizes for guessing. It wouldn’t be hard to guess that the output would be “Student”. So what is the surprise factor.

Let me add some more constraint to the code. What could be the output is the code was compiled on Visual Studio 2017, v15.5.x ? Would your answer change ?

If you were to say that you answer would still be the same, then here is the surprise for you. This is a bug on the C# compiler, which results in compiler error when you use nested properties /sub expression of the format X.Y.Z.

CS0120: An object reference is required for the non-static field, method, or property 'C.Instance'

This bug was fixed in 15.7.x, and anyone using a Visual Studio with version 15.7.x or above, would be able to see the desired result of “Student”.

If you are one of those lucky ones as yours truely, then you are in for an unusual compiler error. If you are interested to read more on the issue, please follow the issue on Github here.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s