Inspecting the code repository of a client, I found something like this:
var customer = new { Id = default(int), Name = default(string) }; var list = new int[0].Select(i => customer).ToList();
I confess that I needed some time to understand it. But, after some consideration, I figured out that what this code is doing is to create an empty strongly typed list of … an anonymous type.
Smart code. Yeah! But, please, don’t do that.
6 respostas
It’s clear for me that’s it’s bad thing from a design view, but what’s about the performance ?
Allocations are not good for performance : array, enumerator (structure, but), closure,..
And… The “model” instance
Shit happens…
Should we change anonymous by nested private class and new int[0].Select(…) by Enumerable.Repeate(…, 0) ?
Is ToList() (or ToArray) itself a problem as I already have a IEnumerable after Select ? ToList helps while debugging, should I remove all unecessary of them?
What about using an array for initializing the list? hehehe
https://dotnetfiddle.net/p4d0wu