Can a conforming C# compiler optimize away a local (but unused) variable if it is the only strong re

Posted by stakx on Stack Overflow See other posts from Stack Overflow or by stakx
Published on 2010-04-30T07:02:43Z Indexed on 2010/04/30 7:07 UTC
Read the original article Hit count: 193

The title says it all, but let me explain:

void Case_1()
{
    var weakRef = new WeakReference(new object());

    GC.Collect();  // <-- doesn't have to be an explicit call; just assume that
                   //     garbage collection would occur at this point.

    if (weakRef.IsAlive) ...
}

In this code example, I obviously have to plan for the possibility that the new'ed object is reclaimed by the garbage collector; therefore the if statement.

(Note that I'm using weakRef for the sole purpose of checking if the new'ed object is still around.)


void Case_2()
{
    var unusedLocalVar = new object();
    var weakRef = new WeakReference(unusedLocalVar);

    GC.Collect();  // <-- doesn't have to be an explicit call; just assume that
                   //     garbage collection would occur at this point.

    Debug.Assert(weakReferenceToUseless.IsAlive);
}

The main change in this code example from the previous one is that the new'ed object is strongly referenced by a local variable (unusedLocalVar). However, this variable is never used again after the weak reference (weakRef) has been created.


Question: Is a conforming C# compiler allowed to optimize the first two lines of Case_2 into those of Case_1 if it sees that unusedLocalVar is only used in one place, namely as an argument to the WeakReference constructor? i.e. is there any possibility that the assertion in Case_2 could ever fail?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET