Umair Ahmed
Umair Ahmed

Reputation: 11686

Can I call an Action<T> stored as delegate

I am storing Action as Delegate. Also I have the T stored as an Interface.

Is there any way later on I can call the Action and pass the object?

public class MyAction {
    public IMyObject IMyObject { get; set; }
    public Delegate myDelegate { get; set; }
    public Type IMyObjectType { get; set; }
}

Where IMyObject is an empty interface

public interface IMyObject { }

I create MyAction instance from Action callback

public static MyAction Factory<T>(Action<T> callback) {
            return new MyAction() {
                myDelegate = callback, IMyObjectType = typeof (T)
            };
        }

Is is possible to call the delegate and pass IMyObject?

Later On I set the IMyObject before trying to call the Delegate(Action)

Upvotes: 2

Views: 110

Answers (3)

Stefan Steinegger
Stefan Steinegger

Reputation: 64648

Make MyAction generic as well

class MyAction<T> where T : IMyObject
{
   public T IMyObject { get; set; }
   public Action<T> action { get; set; }
   public Type IMyObjectType { get { return typeof(T); }
}

The problem is that you can't create the MyAction without know the type of the argument at compile time, unless you create it using reflection (which may be useful if you call the action multiple times and want to optimize execution).

Call the action using DynamicInvoke (which is using reflection and is very slow).

You could also consider making it a Action which includes the arguments. It depends on your requirements.

myDelegate = () => callback(argument);

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1064114

If the type isn't fixed (as in: it is just Delegate, and you can't know the T), then you can use:

action.myDelegate.DynamicInvoke(args);

but that is relatively slow. If you are doing this lots, you would want to avoid that. Frankly, it would be more efficient to just use an Action<object> (or similar) throughout, and cast inside the callback - then your code would know the delegate type and could use regular invoke.

Upvotes: 2

Gusdor
Gusdor

Reputation: 14332

You have to use Delegate.DynamicInvoke to invoke an untyped Delegate.

Upvotes: 0

Related Questions