Make sure the operator is not optimized off

I use an API where, unfortunately, calling the get get access method has a side effect. How can I make sure that:

public void Foo() { var x = obj.TheProp; // is it guarnateed to be accessed? } 

not optimized by the compiler?

+5
source share
1 answer

This will not be optimized - the getter is a method and will be called, although the JIT may choose to "embed" it a lot, if it is simple, perhaps eventually (and completely theoretically), ending just with a null-reference check if TheProp does nothing special interesting. What can happen is that the “thing returned” (the code is stored in x ) has the right to garbage collection until the end of the method; this is rarely a problem, with the exception of things like mutexes outside the process; in this case you can do things like:

 var x = obj.TheProp; // long-running code here GC.KeepAlive(x); 

Please note that if x entered, it will force it to be boxed, which is not ideal.

However: the above is not intended to ensure that TheProp actually called; it is intended for a specific set of garbage-related scenarios.

+6
source

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


All Articles