1

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.

Community
  • 1
  • 1
Jsinh
  • 2,539
  • 1
  • 19
  • 35
  • 2
    What exactly is your question? Searching the web for "C# new dynamic" gives [How to dynamic new Anonymous Class?](http://stackoverflow.com/questions/3740021/how-to-dynamic-new-anonymous-class), for example, and yes, `var foo = new { bar = "baz" }` seems to do what you want. – CodeCaster Nov 24 '14 at 12:15
  • See http://stackoverflow.com/a/392163/1453076 – Vladimirs Nov 24 '14 at 12:16
  • just {...} @GrantWinney – Jsinh Nov 24 '14 at 12:18
  • 1
    "Is there any ways I can create a anonymous type without declaring its type": how would a type be anonymous if you did declare its type? – Chris Nov 24 '14 at 12:19
  • My question is ask and confirm that a {...} keyword or operation does not exist and if we want to do something similar to the question asked in that test - the way to do is would be using dynamic - confirmation (example would be good to add). @CodeCaster – Jsinh Nov 24 '14 at 12:19
  • @Chris you are going literal. Please understand it from programming context. I was trying to understand if we do not declare its type then it would be instantiated anonymously and then at runtime when we assign a value it understand its type based on the value assigned - something like this.. – Jsinh Nov 24 '14 at 12:23
  • You can only instantiate new instances of anonymous types using the `new` operator, in conjunction with the specifier `{...}`. http://msdn.microsoft.com/en-us/library/fa0ab757.aspx – Jodrell Nov 24 '14 at 12:23
  • @Jsinh: I am looking at it from a programming context. You seem to be confusing dynamic and anonymous types. `dynamic` does indeed allow you to at runtime determine what a type is. An anonymous type however is determined and fixed at compile time. You may not have specified all the details of the object but the compiler inferred them all and created a type for you that matches what you wanted. This type has no name that you can see which is why it is "anonymous". – Chris Nov 24 '14 at 12:38
  • 1
    `var someVariableName = new {};` will exactly create an anonymous type and the fact you have this in the question and then ask how to do this makes me think that you may be misunderstanding something more fundamental than the question is asking. Or is it just that you are taking `{...}` literally and not trying something like `new {Property1="Test", Property2=10}`? – Chris Nov 24 '14 at 12:41
  • 1
    Without reference to the original question from Smarterer, this question is a bit of a mess. Anonymous types need to be declared *structurally* (properties, their types and names). You cannot create an anonymous type without this as the compiler cannot do the work required. If you are using the word "anonymous" interchangeably with the concept of a type that can have members dynamically added and removed from it, then don't, C# uses anonymous for something stricter. `dynamic` has an `ExpandoObject` implementation for the JavaScript style prototypical stuff. – Adam Houldsworth Nov 24 '14 at 13:54
  • 1
    If you are referring to needing the `new` keyword, then unless something has changed in the absolute latest C# version, it is required. There is no point in declaring the type before you need to create one, because the compiler does this at compile time anyway, so it boils down to being a purely syntax choice. Supporting an additional mechanism (omitting `new` and just defining structure) is just cost with no benefit. Not to mention, similar syntax styles are also used for many areas, such as manual scoping: `{ /* My code statements */ }` – Adam Houldsworth Nov 24 '14 at 13:56
  • @Chris - I am taking {...} literally - as suggested (to be answer) by the skill test questionare. But thanks I was not aware of the new {} way of creating anonymous type. I will give it a try as soon as i get my hands on PC. – Jsinh Nov 24 '14 at 13:57
  • 1
    @Jsinh `new { }` is the *only* way to create an anonymous type. – Adam Houldsworth Nov 24 '14 at 13:58
  • Chris and @AdamHouldsworth - Agree with you both, if one of you guys can add it properly as answer so can conclude on it and can be a reference for others who get confused by that question on Smarterer. – Jsinh Nov 24 '14 at 14:02
  • @Jsinh Submit a bug report to Smarterer, it's just a wrong answer (by the sounds of it) and should be corrected at source. This question, IMO, should be closed off. – Adam Houldsworth Nov 24 '14 at 14:20

3 Answers3

5

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.

tolanj
  • 3,651
  • 16
  • 30
  • The compiler even matches types that have the same properties, of the same type, in the same order so that it can re-use an existing one. I'm not certain, but I think I remember seeing a ticket when Roslyn was released trying to change it so that the order of properties doesn't matter, just the name and type, when matching "like for like" anonymous types. – Adam Houldsworth Nov 24 '14 at 13:50
1

Use the keyword var

var x = new {value = 3, name = "lol"};
Console.WriteLine(x.value); //prints 3
Console.WriteLine(x.name); //prints lol
sQuir3l
  • 1,373
  • 7
  • 12
1

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.

Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187
  • Thanks, I am going to take up that skill test further and if i get to see that question again I am going to take Screenshot and post it here. But atleast based on current discussion I can be sure that there is no way i can initialize a anonymous type as "new {...}" literally. Thanks all !! And I can also report them that the question is not holding the right answer. – Jsinh Nov 24 '14 at 14:45
  • I would argue, pedantically, that the 'new ' makes (as it always does) an _instance_ of a type and as such { Name = "Adam", Age = 29 } is the entirety of the syntax that could be considered to contain the 'type definition', thus the Smarter answer is correct as it goes, though lacking in details. All semantics though. – tolanj Nov 24 '14 at 15:37
  • @tolanj Well, the latter doesn't compile without the former, so a question trying to teach you something that doesn't compile and claim it is correct is pretty much wrong IMO, but yes, without the exact question wording, the `{ }` part is what identifies the anonymous type. – Adam Houldsworth Nov 24 '14 at 15:38