Reputation: 37366
Is it bad to use anonymous types in C#?
Upvotes: 14
Views: 7773
Reputation: 19620
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.
Upvotes: 15
Reputation: 754763
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.
Upvotes: 13
Reputation: 1296
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.
Upvotes: 7
Reputation: 76001
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.
Upvotes: 8
Reputation: 61437
No, it is not. They are code generated classes at compiletime and perform as well as normal classes.
Upvotes: 25