Jamie Jamie - 4 months ago 13
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?


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.