37

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?

mavnn
  • 9,101
  • 4
  • 34
  • 52

4 Answers4

42

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;
LukeH
  • 263,068
  • 57
  • 365
  • 409
  • 1
    Yep, was typing something along these lines, when you submitted your answer. I think this is the best approach in this scenario. +1 – Andrew Savinykh Jun 07 '11 at 08:58
41

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"));
Pharaz Fadaei
  • 1,605
  • 3
  • 17
  • 28
12

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.

thekip
  • 3,660
  • 2
  • 21
  • 41
  • 2
    This is probably the cleanest solution to the problem. You also don't end up with 10 parameters but one. – Pierre Feb 07 '18 at 09:30
0

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
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272