Assume I have a tool that automatically removes C# code that is detected by the compiler as unreachable. Is there a situation in which such operation can get me into trouble? Please share interesting cases.
Here's the interesting example. Consider a function like this:
public static IEnumerable<int> Fun()
{
if (false)
{
yield return 0;
}
}
The line with yield
is detected as unreachable. However, removing it will make the program not compilable. yield
contained in the function gives the compiler information to reorganize the function so that not doing anything just returns the empty collection. With yield
line removed it looks just like ordinary function with no return while it's required.
As in the comment, the example is contrived, however instead of false
we could have a constant value from other, generated project etc (i.e. such piece of code wouldn't look so obvious as in this case).
Edit:
Note that the yield
construct is actually very similar to async/await
. Yet with the latter creators of the language took a different (IMO better) approach that prevents such scenarios. Iterator blocks could be defined in the same way (using some keyword in function signature instead of detecting it from the function body).
I wouldn't do this automatically, for reasons mentioned in other answers, but I will say here that I'd have a strong bias towards removing unused code over keeping it. After all, tracking obsolete code is what source control is for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With