Giovanni Giovanni - 1 year ago 103
C# Question

How to create a list of anonymous functions/delegates C#

I have a list object like so

private List<Func<int, double, char, string, string>> FuncList;

And have been attempting to add items to this list using delegates and anonymous functions. The problem is, when I attempt to make a function that has this type, I must return a function from that function. I'm managed to do this recursively, but this throws it into an infinite loop. Is it possible to add functions to this list, and if so how?

I'm attempting to add functions that are passed into a delegate like so

public delegate Func<int, double, char, string, string> funcDelegate(someFunc);

And then do something like this


How would you write someFunc so that this code would work.

My failed attempt at writing a function that returns the correct type is like so, this does not work as it's recursive with no stopping case.

public Func<int, double, char, string, string> SomeFunc(int i, double d, char c, string s1, string s2)
return this.SomeFunc(i,d,c,s1,s2);

Answer Source

First, your method doesn't have the right signature. The last generic parameter in Func<> is the return type. Action<> is a generic delegate type that returns void.

Second, the whole point of using Func<> is that you DON'T need to create new types of delegates - Func<> is already a delegate.

Here's an example:

    // A list of delegates that accept an integer and return a string
    private static List<Func<int, string>> delegateList = new List<Func<int, string>>();

    public static string Foo(int x)
        return $"Foo {x}";

    public static void Test()
        delegateList.Add(Foo); // Add a delegate to a named method
        delegateList.Add(delegate(int x) { return $"Bar {x * 2}"; } ); // Add a delegate to an anonymous method
        delegateList.Add(x => $"Baz {x * 3}"); // Add a delegate to a lambda
        foreach (var del in delegateList)

In your example, you are declaring a delegate to a function that returns another delegate, but that doesn't seem to be what you're trying to accomplish.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download