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.

More posts in "Things you should not do with C#" series:

  1. It’s clear for me that’s it’s bad thing from a design view, but what’s about the performance ?

  2. 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?

Leave a Reply

Your email address will not be published. Required fields are marked *