Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is removing unreachable code always safe?

Tags:

c#

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.

like image 821
konrad.kruczynski Avatar asked Sep 24 '14 15:09

konrad.kruczynski


2 Answers

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).

like image 62
konrad.kruczynski Avatar answered Oct 01 '22 08:10

konrad.kruczynski


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.

like image 34
Joel Coehoorn Avatar answered Oct 01 '22 07:10

Joel Coehoorn