Why does a delegate with no parameters compile?

Posted by Ryan on Stack Overflow See other posts from Stack Overflow or by Ryan
Published on 2010-04-20T21:36:52Z Indexed on 2010/04/20 21:43 UTC
Read the original article Hit count: 238

Filed under:
|

I'm confused why this compiles:

    private delegate int MyDelegate(int p1, int p2);

    private void testDelegate()
    {
        MyDelegate imp = delegate 
        {
            return 1;
        };
    }

MyDelegate should be a pointer to a method that takes two int parameters and returns another int, right? Why am I allowed to assign a method that takes no parameters?

Interestingly, these doesn't compile (it complains about the signature mismatches, as I'd expect)

    private void testDelegate()
    {
        // Missing param
        MyDelegate imp = delegate(int p1)
        {
            return 1;
        };

        // Wrong return type
        MyDelegate imp2 = delegate(int p1, int p2)
        {
            return "String";
        };
    }

Thanks for any help!

Ryan

© Stack Overflow or respective owner

Related posts about c#

Related posts about delegates