Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will the C# compiler remove unused local if it is assigned a property?

This might be a silly question. I know that compiler will remove unused locals. But if I write my code like this:

class MyClass
{
    public int SomeProperty
    {
        get
        {
          ...
        }
    }

    public void SomeFunction ()
    {
       //will this line be removed if i is never used?
       int i = SomeProperty;
       ...
    }
}

I am wondering that if i will be removed by compiler because of optimization. There is logic inside the getter of SomeProperty that I wish to execute. If i will be removed, I have to change SomeProperty to a function.

Btw, is there a way to know which line will be optimized by compiler?

like image 765
Xinchao Avatar asked May 03 '13 09:05

Xinchao


1 Answers

I would suggest that what the compiler does is not important. This is bad design.

If calling a getter has important side effects then it should probably not be a getter. The most a getter should probably be doing is lazy initialising something and this shouldn't be important since if it doesn't happen it will just get done by the next thing to get it.

I don't know what you are doing but it probably should be refactored into its own method that can be called explicitly at that point.

The other major concern is relate to readability. Anybody seeing the line int i = SomeProperty; when i is never used again might well decide that the line is pointless and does nothing and thus remove it from the code causing whatever unexpected errors to arise. You would be better off calling a method like LogicExtractedFromProperty() so it is obvious you are doing something.

The compiler might (or might not, I don't know or care) do the right thing but a person may well not.

like image 67
Chris Avatar answered Sep 18 '22 02:09

Chris