I'm trying to learn the "functional" part of C#/.Net for work, and I'm not sure if this is a good way to write this statement.
I was also trying to reduce duplicated code while not introducing too many allocs. From my understanding everything created by new here will be flagged for release once the .ForEach() is finished. Or the compiler optimizes the news out.

enum Fruits {Apple, Banana, Pear, Peach, Orange, Lychee}

new List<Fruits>
        Fruits.Apple, Fruits.Banana, Fruits.Orange, Fruits.Lychee
    .ForEach(x => Eat(x));

Just to note. I'm aware I could have written it the foreach loop way aswell

foreach (var x in new List<Fruits>{Fruits.Apple, Fruits.Banana, Fruits.Orange, Fruits.Lychee})
  • 2
    \$\begingroup\$ You're worried about things that should only worry you in extreme situations: stackify.com/premature-optimization-evil . First and foremost write readable code, and only if you are encountering (significant) performance issues, start optimizing code. \$\endgroup\$
    – BCdotWEB
    Dec 30 '21 at 8:33

I can see only a single new there so it doesn't really matter in this context. If you have code that creates millions of them I suggest asking a new question with the actual code. As far as this one is concerned you'll fine with a single line where you let Enum grab all the values and pass Eat to the Select without the lambda as its signature matches the lambda.

var results = Enum.GetValues<Fruits>().Select(Eat);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.