"dynamic" for anonymous delegates?

2.6k views Asked by At

I wonder if there is a possibility to make the "dynamic" type for variables work for anonymous delegates.

I've tried the following:

dynamic v = delegate() {
};

But then I got the following error message:

Cannot convert anonymous method to type 'dynamic' because it is not a delegate type

Unfortunately, also the following code doesn't work:

Delegate v = delegate() {
};
object v2 = delegate() {
};

What can I do if I want to make a Method that accepts any type of Delegate, even inline declared ones?

For example:

class X{
    public void Y(dynamic d){
    }
    static void Main(){
        Y(delegate(){});
        Y(delegate(string x){});
    }
}
3

There are 3 answers

7
Adam Houldsworth On BEST ANSWER

This works, but it looks a little odd. You can give it any delegate, it will run it and also return a value.

You also need to specify the anonymous method signature at some point in order for the compiler to make any sense of it, hence the need to specify Action<T> or Func<T> or whatever.

Why can't an anonymous method be assigned to var?

    static void Main(string[] args)
    {
        Action d = () => Console.WriteLine("Hi");
        Execute(d); // Prints "Hi"

        Action<string> d2 = (s) => Console.WriteLine(s);
        Execute(d2, "Lo"); // Prints "Lo"

        Func<string, string> d3 = (s) =>
        {
            Console.WriteLine(s);
            return "Done";
        };
        var result = (string)Execute(d3, "Spaghettio"); // Prints "Spaghettio"

        Console.WriteLine(result); // Prints "Done"

        Console.Read();
    }

    static object Execute(Delegate d, params object[] args)
    {
        return d.DynamicInvoke(args);
    }
2
user703016 On

If you declare a type for each of your delegates, it works.

// Declare it somewhere
delegate void DelegateType(string s);

// The cast is required to make the code compile
Test((DelegateType)((string s) => { MessageBox.Show(s); }));

public static void Test(dynamic dynDelegate)
{
    dynDelegate("hello");
}
1
user9285847 On
Action _;
dynamic test = (_ = () => Console.WriteLine("Test"));
test() // Test