Jamie
Jamie

Reputation: 1657

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?

Upvotes: 2

Views: 2213

Answers (2)

vgru
vgru

Reputation: 51224

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.

Upvotes: 3

Janne Matikainen
Janne Matikainen

Reputation: 5121

Make an interface which you can pass as a parameter for the delegate, then implement the interface with the class you are passing the delegate to, and pass the instance when you are invoking the delegate.

Upvotes: 1

Related Questions