• Feeds

    Subscribe in a reader

  • Ads

C# Feature Request

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.

#1 John Rusk on 4.23.2004 at 4:50 PM

Steve,I like your suggestion.A variation of it occurred to me recently.I've posted it here:http://homepages.paradise.net.nz/jjrusk/tech/id58.htmJust thought I'd share the link, in case you're interested.John

#2 John Rusk on 12.08.2004 at 11:25 PM

Hello Steve,I posted the above comment over 6 months ago, but I've only just thought of the right way to implement what I suggested!FYI I've written it up here: www.agilekiwi.com/.../compiler_checke