Search code examples
c#variablesusinganonymous-types

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


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.


Solution

  • 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.