I understand that an action is just a pre-declared delegate that can accept a single parameter of the type defined. so Action<String> represents a method that has no return and accepts a single string parameter. So far so good.
In my code i have this method:
public void Send<TMessageType>(Types.MessageBase<TMessageType> message)
{
Console.WriteLine("Message Sent");
List<Delegate> subscriptions;
if (register.TryGetValue(typeof(TMessageType), out subscriptions))
{
foreach (Delegate subscription in subscriptions)
{
Console.WriteLine("Invoking....");
subscription.DynamicInvoke(message);
}
}
}
All of the Delegates in the subscriptions variable were actually instantiated as actions. My question is, why does my code work? Why dont i need to cast my delegate back into an action (it would be Action<TMessageType>), before i can use it? surely the default delegate type has no idea what parameters to expect?
Well the short answer is because your call to
DynamicInvokeis a late-bound call and doesn’t actually know whether or not it even needs parameters.MSDN
As a side note:
Given that you have knowledge of the type being passed to the
Actionyou should probably refactor your code to directly invoke the actions and not useDynamicInvokeif you can avoid it as there will be a performance impact. If you cannot avoid it due to restrictions not shown then so be it.Of course I don’t know what would be involved in refactoring the
TryGetValuecall.