views:

236

answers:

2

When you create a new anonymous object using the following syntax:

string name = "Foo";
var myObject = new { name };

You get an object with a property named 'name':

myObject.name == "Foo"; //true

What method does C# use to extract the variable name?

+5  A: 

Basically, that expression is equivalent to

new { name = name }

since no explicit property name is provided.

The C# compiler generates a class at compile time with a name property. It infers the property name from the variable name (which it obviously sees). Everything is statically typed at compile time. Nothing special is performed at run time (except initialization of the anonymous class instance). No method is called on anything.

Mehrdad Afshari
OK. That makes sense. I was making it more complicated in my head, even though I knew it was done at compile time. I guess my real question was what's the best way to get the name of a variable and I figured however it was done by the compiler would be the best way.
John Sheehan
Which is obviously not directly translatable to C# :)
John Sheehan
You can see how Mehrdad is right from that the compiler complains when you do `object obj = new { "Foo" };`. It can't infer any name from what you've used. `object obj = new { name = "Foo" };` works fine again.
Joren
+5  A: 

If your question is "how do I get the name of a variable?" (as you mention in your comment above) then this is the wrong question to ask, because this doesn't get the name of a variable in the first place. A projection initializer need not be a variable at all. All it needs to be is either an identifier, or an expression followed by a period followed by an identifier. The name used by the projection initializer is the identifier.

If your question actually is "how do I get the name of a variable?" the answer is "you don't, because variables do not necessarily have unique names". A variable can have zero, one, or many names associated with it, and those names are only known at compile time (or by the debugger consuming information emitted by the compiler); the names do not exist at runtime.

Eric Lippert