C# replace foreach with for

I'm currently looking into a way of replacing all foreach loops with for loops in order to see the if I could gain some minor benefits in some legacy code that creates a ton of garbage. The thing is that it would take days to change all by hand in order to measure if the garbage removed would impact the performance in a bad way instead, so I scripted a parser for making a simple swap. The thing is that some cases uses list others arrays and some ienumerable. So the question I have is, can I read a c# file from another project and evaluate the type of container used to switch iteration programmatically instead to save time? Even if it's a bad idea it would be a fun experiment to try and automate something like this.

Feb 5, 2025 - 23:18
 0
C# replace foreach with for

I'm currently looking into a way of replacing all foreach loops with for loops in order to see the if I could gain some minor benefits in some legacy code that creates a ton of garbage.

The thing is that it would take days to change all by hand in order to measure if the garbage removed would impact the performance in a bad way instead, so I scripted a parser for making a simple swap. The thing is that some cases uses list others arrays and some ienumerable. So the question I have is, can I read a c# file from another project and evaluate the type of container used to switch iteration programmatically instead to save time?

Even if it's a bad idea it would be a fun experiment to try and automate something like this.