Will the C # compiler delete unused local ones if a property is assigned to it?

This may be a dumb question. I know that the compiler will remove unused locales. But if I write my code as follows:

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 if i will be removed by the compiler due to optimization. Inside the SomeProperty receiver SomeProperty is logic that I want to execute. If i is deleted, I have to change SomeProperty to a function.

Btw, is there any way to find out which string will be optimized by the compiler?

+6
source share
1 answer

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

If a getter call has important side effects, then it probably shouldn't be a getter. Most likely, the getter is likely to be lazy, initializing something, and this should not be important, because if this does not happen, it will simply be done next to get it.

I do not know what you are doing, but it probably should be reorganized into its own method, which can be explicitly called at this point.

Another major issue is readability. Anyone who sees the string int i = SomeProperty; when i will never be used again, it may well decide that the line is meaningless and does nothing and, thus, removes it from the code, causing unforeseen errors. You would be better off calling a method like LogicExtractedFromProperty() , so it’s obvious that you are doing something.

The compiler can (or cannot, I don’t know and don’t care) do the right thing, but a person can do it wrong.

+9
source

Source: https://habr.com/ru/post/944189/


All Articles