Jamie Jamie - 3 months ago 6
C# Question

Accessing class members in a delegate in C#

I'm trying to create a class whose frame update method can be defined by a delegate; however, I've found that a delegate cannot access its class's members. Is there any way to do this? Is there an alternate method anyone can suggest to have a dynamically defined method like this?

Answer

You can pass the parent instance reference to the delegate as a parameter, i.e.

class Parent : IParent
{
    readonly Func<IParent, IFrame> _render;
    public IFrame Render()
    {
         return _render(this);
    }
}

Of course, unless the render delegate is also a part of the class or its internal classes, it will only be able to access public members.

Note that it's a good idea to use an interface as the parameter type, and to choose a minimum interface which is needed by the delegate (and expose nothing more), as this will allow you greater extensibility.