Home > OS >  Do Func and Action delegates become null if the source object becomes dereferenced?
Do Func and Action delegates become null if the source object becomes dereferenced?

Time:07-07

Define these variables in Class A:

public int CubeAnInt32(int n)
{
    return n * n * n;
}

And these variables in Class B:

public void CubeAnInt32WithDelegate(int k, Func<int, int> delg)
{
    return delg(k);
}

And an overall scope:

/// Note that this is outside the scope of SomeArbitraryCallback()
Func<int, int> cube = default;

public void SomeArbitraryCallback()
{
    var refWithinScope = new ClassA();
    cube = refWithinScope.CubeAnInt32;
    return;
}

public void AnotherCallbackPerformedAfter()
{
    var cubeDependent = new ClassB();

    /// Does this throw a NullReferenceException because of 'cube'?
    /// Has the delegate assigned to 'cube' been dereferenced?
    var result = cubeDependent.CubeAnInt32WithDelegate(0, cube);
    return result;
}

Will a delegate whose object has been "de-scoped" (i.e. cube) be dereferenced? Or will this delegate reference the assigned object and prevent it from being GC'd?

CodePudding user response:

As per https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/ - "A delegate is a type that represents references to methods" (emphasis is mine).

So as long as your delegate (cube) remains in scope, a reference is held and refWithinScope (of type ClassA) will not be collected.

Whether you want to have this sort of design is a different discussion: looks like a good candidate for introducing subtle, unintended bugs in future re-factors.

  • Related