Nic Foster
Nic Foster

Reputation: 2894

Generic delegates, C# 3.5

I have multiple classes with a common base type. I want a delegate that takes any subclass of the base type as an argument. I pictured it as being something like this, but this doesn't work:

private delegate void ActionDelegate(BaseAction action);

class ChildAction : BaseAction
{
}

public static class SomeOtherClass
{
    public void ProcessChildAction(ChildAction childAction)
    {
    }

    public void Main()
    {
        ChildAction childAction = new ChildAction();

        ActionDelegate actionDelegate = ProcessChildAction;
        actionDelegate(childAction);
    }
}

I've tried this:

private delegate void ActionDelegate<T>(T action);

but that seems like it would let any kind of class through, where I just want any subclass of BaseAction. Even so, I can't seem to get it to compile when I do this so I'm not sure if that's the right way to do this anyway.

Also, I'm using Unity, so I'm limited to C# 3.5.

Upvotes: 1

Views: 106

Answers (1)

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

Use constraint:

private delegate void ActionDelegate<T>(T action) where T : BaseAction;

Upvotes: 4

Related Questions