Reputation: 9469
I have a "dispatch map" defined as such:
private Dictionary<string, Func<DynamicEntity, DynamicEntity, IEnumerable<DynamicEntity>, string>> _messageProcessing;
This allows me to dispatch to different methods easily depending on the name of the DynamicEntity instance.
To avoid being hated by everyone who maintains the code forever more, is there any way of naming the parameters in the Func to give some clue to which DynamicEntity is which?
Upvotes: 43
Views: 17986
Reputation: 1827
As of C# 7 you can achieve it using named tuples this way:
Func<(string firstName, string lastName), string> f = (data) => data.firstName + data.lastName;
f(("Foo", "Bar"));
Upvotes: 50
Reputation: 269428
You can't do it with the built-in Func
types, but it's easy enough to create your own custom delegate type and use it in a similar way:
_messageProcessing.Add("input", (x, y, z) => "output");
_messageProcessing.Add("another", (x, y, z) => "example");
// ...
delegate string DispatchFunc(DynamicEntity first, DynamicEntity second,
IEnumerable<DynamicEntity> collection);
Dictionary<string, DispatchFunc> _messageProcessing;
Upvotes: 48
Reputation: 134891
I don't think that's possible unfortunately. Once you have an instance of a delegate that was created from a lambda or other method, you loose the argument names that went along with it. So no intellisense support.
However you could always find out the names of the parameters by inspecting the parameters of the associated MethodInfo
object for the instance. You just won't get the compile-time support for it.
e.g.,
Action<string, int> myAction = (myString, myInt) => { };
var parameters = myAction.Method.GetParameters();
var paramNames = String.Join(", ", parameters.Select(p => p.Name)); // myString, myInt
Upvotes: 0
Reputation: 3768
You can create a class which contains your 'parameters' and supply that to the func? That way you can name them anything you want.
As far as I know you can't name them inline.
Upvotes: 14