lundi 2 août 2021

Get a property name from a lambda expression *without* an object instance

By now I think many asp.net web developers are familiar with methods that take a lambda expression and examine the call stack to determine which property was used. It allows you to write code like this...

var x = new X()
CallMethodWithProperty(x => x.Y);

This lets you pass in X.Y with relatively succinct syntax. Another way you see this done sometimes is using two nameof operators, one to look up the class, and the other to look up the property. It's more verbose, but does work.

CallMethodWithNames(nameof(X), nameof(X.Y));

Great and fine. My question is: how can you do this without an object reference? Let's say you do not have an instance of the X type, and you want to reference the X.Y property. Could you do that just as succinctly?





Aucun commentaire:

Enregistrer un commentaire