I have classes that described below. Does GC collect field1 and field2 from object “a” in class “C” ?
public abstract class A
{
//some methods and properties
}
public class B : A
{
public int field1 { get; set; }
public int field2 { get; set; }
}
public class C
{
public A a { get; set; }
private System.Windows.Forms.Timer timer;
public C()
{
a = (A)typeof(B).GetConstructor(bla, bla, bla).Invoke(bla, bla);
((B)a).field1 = 25;
timer = new System.Windows.Forms.Timer();
timer.Enabled = true;
timer.Interval = 10000;
timer.OnTick += (o, e) => { Console.WriteLine(((B)a).field1); };
}
}
As long as
ais in scope,field1andfield2will remain in scope. As long as theTimercontinues to run and referencea, or a reference to your instance ofCexists,awill remain in scope.I think what you’re asking is if they’ll be lost because we only statically know of the instance of
Aas an instance ofA, not as an instance ofB. The answer to that is no, the info remains in scope.