-2

First of all, I don't even know what to use when passing on 4 parameters but no return value, I'll just use Func as an example.

I do not want to use Dictionary.Add to insert my function, I want it to be inside while initializing the dictionary.

Dictionary<string, Func<int, int, int, int>> types = new Dictionary<string, 
{"Linear", Func<int, int, int, int>> //idk how to write this part
{ 
    code here
}}
BJ Myers
  • 6,617
  • 6
  • 34
  • 50
Nils
  • 5
  • 1
  • Have you read the [documentation](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-initialize-a-dictionary-with-a-collection-initializer)? – BJ Myers Oct 01 '17 at 16:11
  • Did you forget to write the method that can be called through this dictionary? That is what is missing, its name. – Hans Passant Oct 01 '17 at 16:14

1 Answers1

3

For a Func like the one you have in your question, this should work:

var myDict = new Dictionary<string, Func<int, int, int, int>>()
{
    {"Linear", (int a, int b, int c) => { return 0; } }
};

Note that you always need to have a return in your function.

If you want something that does not have a return value, you shouldn't use a Func, but an Action instead:

var myDict = new Dictionary<string, Action<int, int, int, int>>()
{
    {"Linear", (int a, int b, int c, int d) => { } }
};

Unlike functions, actions do not return anything.

Note the difference in meaning between Action<int, int, int, int> and Func<int, int, int, int>. In the former, the last int indicates the type of the 4th parameter, whereas in the latter it indicates the return type.

stelioslogothetis
  • 9,371
  • 3
  • 28
  • 53