One of my coworkers (one Mr. Brian Vargas, who has a blog but never posts to it) and I were having a conversation this afternoon about how much we wished C# had a nameof() operator. The job of this operator would be to “quote” a lexical token that would otherwise compile into a member ref and turn it into a string (being the name of the member being referenced). I think this would make consuming the Reflection API's a lot cleaner.
For example, to get a PropertyInfo instance for a property named “Foo”, I currently say:
Type t = this.GetType();
t.GetProperty(“Foo”);
It would be better for me to be able to say:
Type t = this.GetType();
t.GetProperty( nameof(this.Foo) );
The big benefits to this:
· I get compile-time checks for the Reflection API. If my type doesn’t expose a property named “Foo”, I’d find out at compile time instead of runtime.
· Intellisense.
It also simplifies calling methods that wrap the Reflection API’s. Let’s say I had a function that mapped ASP.NET controls to properties on an object. The signature looks like this:
public void MapControlToProperty( Control c, Object o, string propertyName )
Underneath the hood, this function uses the GetProperty() API. Callers of this code have to say something like:
MapControlToProperty( txtFirstName, myPersonInstance, “FirstName” );
If the caller fat-fingers the propertyName string, they won’t find out until run-time when this code gets called. It would be much safer if I could use a nameof() operator to say:
MapControlToProperty( txtFirstName,
myPersonInstance,
nameof( myPersonInstance.FirstName ) );
This way, the compiler can enforce the fact that the FirstName property actually exists, and the developer writing the code gets the benefit of Intellisense.
I don’t imagine that this would be that hard to implement – after all, isn’t this basically what the compiler’s doing under the hood when it encounters the delegate keyword? The “magic” is already there – I’d just like to have a way to explicitly access it.
