Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a delegate with no parameters compile?

Tags:

c#

delegates

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

like image 507
Ryan Avatar asked Apr 20 '10 21:04

Ryan


People also ask

How do you pass parameters to delegates?

Delegates in C# are similar to function pointers in C++, but C# delegates are type safe. You can pass methods as parameters to a delegate to allow the delegate to point to the method. Delegates are used to define callback methods and implement event handling, and they are declared using the “delegate” keyword.

What will happen if a delegate has a non void return type?

When the return type is not void as above in my case it is int. Methods with Int return types are added to the delegate instance and will be executed as per the addition sequence but the variable that is holding the return type value will have the value return from the method that is executed at the end.

What is delegate in C# with example?

Unlike C function pointers, delegates are object-oriented, type safe, and secure. The type of a delegate is defined by the name of the delegate. The following example declares a delegate named Del that can encapsulate a method that takes a string as an argument and returns void: C# Copy.

How do you call a delegate function in C#?

Delegates can be invoke like a normal function or Invoke() method. Multiple methods can be assigned to the delegate using "+" or "+=" operator and removed using "-" or "-=" operator. It is called multicast delegate. If a multicast delegate returns a value then it returns the value from the last assigned target method.


1 Answers

Your first example is short-hand syntax if the delegate doesn't need the parameters. If you need even one of them, you need to provide them all, which is why the first part of the second example won't compile.

like image 75
Niall C. Avatar answered Nov 14 '22 23:11

Niall C.