Delegates using a non-static member function->Is the providing Object protected from GC?

  • Thread starter Thread starter Andreas Mueller
  • Start date Start date
A

Andreas Mueller

Hi All,

the following Situation is going through my mind:


class Xox
{
public Xox(){}
public object Foo(){ return null; }
}
class Class1
{
public delegate object Functor();
[STAThread]
static void Main(string[] args)
{
Functor f = new Functor(new Xox().Foo);
// do something with f later on, when
// nobody is referencing the Xox instance anymore
}
}

The newly created Xox object that is used to create the Delegate is not
referenced from anywhere. I would expect that the GC can collect it
anytime it sees fit. Is that true, or is the fact that a delegate is
referencing the Member function protecting it?

Thanks in advance,
Andy
 
Andreas,

The delegate has a reference to the object, so it is not eligible for GC
if all other references are released. Once the reference to the delegate is
freed, then the class with the method referenced by the delegate will be
eligible for GC.

Hope this helps.
 
Andreas Mueller said:
class Xox
{
public Xox(){}
public object Foo(){ return null; }
}
class Class1
{
public delegate object Functor();
[STAThread]
static void Main(string[] args)
{
Functor f = new Functor(new Xox().Foo);
// do something with f later on, when
// nobody is referencing the Xox instance anymore
}
}

The newly created Xox object that is used to create the Delegate is not
referenced from anywhere. I would expect that the GC can collect it
anytime it sees fit. Is that true, or is the fact that a delegate is
referencing the Member function protecting it?

The delegate contains an implicit reference to the instance if is
defined using, unless it's static. So at the moment, the Xox instance
can't be garbage collected. If Foo were static, it could be (and you'd
use just Xox.Foo, of course, not new Xox().Foo).
 
Back
Top