0

Is there a more concise way to add this function to the object list? I'd like to avoid having to assign into the intermediate addFunc variable.

static void Main(string[] args)
{
    List<object> myObjects = new List<object>();

    //myObjects.Add(AddThings);

    Func<int, int, int> addFunc = AddThings;
    myObjects.Add(addFunc);
}

static int AddThings(int x, int y) { return x + y; }
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
ktam33
  • 1,217
  • 12
  • 22

2 Answers2

4

You can cast it:

myObjects.Add((Func<int, int, int>) AddThings);

or

var myObjects = new List<object> { (Func<int, int, int>)AddThings };
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
Lee
  • 142,018
  • 20
  • 234
  • 287
0

You can define delegate:

delegate int AddThingsDelegate(int x, int y);

and then easily add it to your list like:

myObjects.Add(new AddThingsDelegate(AddThings));

For comparison between answers you can read: What is the difference between Func and delegate?

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69