Things you should not do with C#

Creating an empty strongly typed list of … an anonymous type (What?!)

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

6 Comments
  1. Bruno

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

    1. elemarjr

      Allocations are not good for performance : array, enumerator (structure, but), closure,..

      1. elemarjr

        And… The “model” instance

  2. Aroldo Peixe

    Shit happens…

  3. Anderson

    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?

  4. Johnny Santos

    What about using an array for initializing the list? hehehe
    https://dotnetfiddle.net/p4d0wu

Leave a Reply

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