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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With