tags:

views:

164

answers:

6

Is it bad to use anonymous types in c#?

+6  A: 

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
+7  A: 

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

Femaref
+3  A: 

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
Comparable or identical?
Steven Sudit
@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
@Jörg: Thank you for spelling that out here. If you don't mind, I'm going to steal your answer.
Steven Sudit
Anonymous types don't have methods ;-)
macias
@macias: What do you call the default constructor, then? :-)
Steven Sudit
@Steven, a constructor.
macias
@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
+2  A: 

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.

+7  A: 

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
A: 

I suppose the only downside you might get is a bigger executable file (compared to reusing existing types). That would probably not be noticeable unless you have hundreds or thousands of them though...

Xavier Poinas