I have been investigating C# delegates and coming from a python angle I wondered what would happen if I treated a static method as a first-class citizen and just passed it directly as an arg without wrapping in a delegate type.
Surprisingly it seemed to work. However when trying to use the same approach with multicasting, it failed with:
[CS0019] Operator '+' cannot be applied to operands of type 'method group' and 'method group'
My question is what is going on behind the scenes to allow me to pass staticMethod
directly as an argument and why won't that same process allow me to multicast the method directly in a similar fashion to what I can achieve using the delegate type?
using System;
namespace Delegates
{
class Program
{
public delegate void Func();
public static void staticMethod()
{
Console.WriteLine("In staticMethod()");
}
public static void executeFunc(Func f)
{
f();
}
static void Main(string[] args)
{
Func f = staticMethod;
executeFunc(f);
// why cant' we just pass the static method as a first-class citizen and bypass any delegate creation?'
executeFunc(staticMethod); // we can - this works
executeFunc(f + f);
executeFunc(staticMethod + staticMethod); // but this doesn't
}
}
}
possibly its some sort of implicit cast as the following seemed to work:
executeFunc((Func)staticMethod + (Func)staticMethod);