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