Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access object from delegate containing the referenced method

Tags:

c#

I need to know if it's possible to access the underlying object that contains the method referenced by a delegate?

I know that the object is captured in the delegate because it is required when invoking the method.

like image 785
Alecu Avatar asked Dec 04 '25 18:12

Alecu


1 Answers

A Delegate references it's target. Of course, static methods have no target, so a null check might be required.

class Program
{
    static void Main(string[] args)
    {
        var container = new Container();

        Func<string> doSomething = container.DoSomething;

        Delegate d = doSomething;

        // This will be the container, but you need to cast.
        var c = (Container)d.Target;

        Console.Read();
    }
}

class Container
{
    public string DoSomething()
    {
        return "";
    }
}

I'm not sure what you are trying to achieve with this, but needing to know about the target type that is fulfilling a delegate reference might be a code smell or an indicator of a design issue.

like image 82
Adam Houldsworth Avatar answered Dec 06 '25 07:12

Adam Houldsworth