using {...} with new to instantiate anonymous type in C#

578 views Asked by At

I recently was trying my skill tests for C# at Smarterer.

I came across a question which says which of the following can be used to create a anonymous type in C# (something similar).

I selected "None of these" (i do not remember other options as it was time based test only had 10 sec).

Once I gave the answer it said that {...} is the right answer.

So i guess something like this:

var someVariableName = new {...}; to create a anonymous type.

I am surprise to see this and binged a bit but was not able to find anything similar to this.

Question: Is there any ways I can create a anonymous type without declaring its type while instantiating using {...} keyword or operator? or the question's correct answer was not "correct"?

This can be done using dynamic keyword if I am not wrong.

3

There are 3 answers

1
tolanj On BEST ANSWER

http://msdn.microsoft.com/en-GB/library/bb397696.aspx is the MS documenation, to quote:

You create anonymous types by using the new operator together with an object initializer. For more information about object initializers, see Object and Collection Initializers (C# Programming Guide). The following example shows an anonymous type that is initialized with two properties named Amount and Message.

C#
var v = new { Amount = 108, Message = "Hello" };

This is NOT a dynamic type, this a specific static type that is 'anonymous', ie you have not given it a name. However the compiler has/will and so v is still strongly typed, you get intellisense and v.FieldIDontHave will give a compiler error.

0
sQuir3l On

Use the keyword var

var x = new {value = 3, name = "lol"};
Console.WriteLine(x.value); //prints 3
Console.WriteLine(x.name); //prints lol
3
Adam Houldsworth On

After spending time in the comments getting to the bottom of this question, I can confirm some of the details.

The Smarterer "answer" stating that just { MyProperty = 2 } was valid syntax for an anonymous type is only half correct. The syntax is required, but it is required in conjunction with the new keyword.

var anon = new { Name = "Adam", Age = 29 };

Attempting the following in VS 2012 will not compile:

// Try and make an anonymous type without new.
var anon = { Name = "Adam", Age = 29 };

// Try and declare an anonymous type prior to "newing" one up.
{ Name = "Adam", Age = 29 };

Again without the exact question and available answers from the other site, it is hard to provide context for the question and subsequent answer on this site. Hopefully this is enough to close it off.