13

Is it bad to use anonymous types in C#?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ryudice
  • 36,476
  • 32
  • 115
  • 163
  • 1
    See [How should anonymous types be used in C#?](http://stackoverflow.com/questions/48668/how-should-anonymous-types-be-used-in-c) – Matthew Flaschen Jun 23 '10 at 23:30

5 Answers5

23

No, it is not. They are code generated classes at compiletime and perform as well as normal classes.

Femaref
  • 60,705
  • 7
  • 138
  • 176
13

They're like other types, in terms of performance.

edit

To be more clear, I should have said that they perform exactly like other types because they are exactly like other types, except for the fact that the compiler generates the name. The only way performance would suffer is if you pass an instance of the anonymous type to another scope, where reflection or dynamic would have to be used just to access the properties. That would be expensive because it involves late binding to resolve everything at runtime.

Steven Sudit
  • 19,391
  • 1
  • 51
  • 53
12

Are anonymous types in themselves bad? No. If they were the C# team certainly wouldn't have wasted their time adding it to the language. Under the hood they just compile down to standard CLR types.

Can anonymous types, like practically every other language feature, be abused to the point of being non-performant. Sure.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
8

An anonymous type in C# is still a static type and accessing its methods and properties is resolved by the compiler. The performance is comparable to explicit types.

Franci Penov
  • 74,861
  • 18
  • 132
  • 169
  • 6
    @Steven Sudit: there is no such thing as an anonymous type in the CLI. In fact, anonymous types in C# are just a fiction: they are in fact named types just like any other, because that is the only type the CLI supports. The only difference is that their name is generated by a random number generator instead of a human. So, yes, the performance of anonymous types is identical to named types because anonymous types *are* named types. – Jörg W Mittag Jun 24 '10 at 04:34
  • 1
    @Jörg: Thank you for spelling that out here. If you don't mind, I'm going to steal your answer. – Steven Sudit Jun 24 '10 at 05:37
  • Anonymous types don't have methods ;-) – greenoldman Jun 24 '10 at 05:59
  • @macias: What do you call the default constructor, then? :-) – Steven Sudit Jun 24 '10 at 15:10
  • @macias: Yes, I also call it a constructor, as that is an accurate description. According to http://msdn.microsoft.com/en-us/library/ms173115.aspx, constructors are methods, so calling it a method would also be accurate. – Steven Sudit Jun 25 '10 at 15:50
6

It's not bad, sometimes it is convinient. For example, when using Linq, instead of creating a class that will be used only once, it's preferable to use anonymous types.

user347594
  • 1,256
  • 7
  • 11