Search code examples
c#delegatesanonymous-functionanonymous-methods

Parameterless anonymous method can be assigned to parametered delegate


class Program{
      static void Main(){
         test11 jhbee = Program.test;  //error
         test11 yep = delegate {  };   //no error

      }
   static void test() { }
}

delegate void test11(int r);

So I have the delegate test11 which returns void and takes 1 parameter.
whn I try to assign a parameterless method to an instance of test11, the compiler, obviously issues an error but when I assign a parameterless anonymous method to an instance of test11, no error is issued.
I mean, I can see that there is no obstacle for it to work but can you please tell me why is this so? Is there a good reason for this?


Solution

  • From the documentation:

    When you use the delegate operator, you might omit the parameter list. If you do that, the created anonymous method can be converted to a delegate type with any list of parameters

    So while it appears that way, the created anonymous method is not really parameterless - its parameter list has just not been defined.

    As for the reason why this is an option, this answer to a related question might help explain it.