I tried to define a delegate override between Int32
and IntPtr
. Why are the following overloads illegal?
public delegate int EnumWindowsCallback (System.IntPtr hWnd, int lParam);
public delegate int EnumWindowsCallback (System.IntPtr hWnd, System.IntPtr lParam);
That looks pretty strange. They are both structs but are different and implement from different interfaces.
Come to think of it, I have never tried to overload a delegate before. Is it even legal, and if so, why?
UPDATE: After going through the answers and some more SO posts, I was baffled that delegates cannot be declared even with a varying number of parameters. I am still wondering why this cannot be resolved at runtime.
You can not define more than one method with the same name, Order and the type of the arguments. It would be compiler error. The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return type.
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. You can declare a delegate that can appear on its own or even nested inside a class.
Only one method can be called using a delegate.
A delegate is a type safe and object oriented object that can point to another method or multiple methods which can then be invoked later. It is a reference type variable that refers to methods.
Come to think of it, I have never tried to overload a delegate before. Is it even legal, and if so, why?
No, it's not legal. You're currently declaring two types with the same fully-qualified name.
The only thing that looks a bit like overloading when it comes to types is if you declare two types which differ in the number of generic type parameters. For example, Action<T>
, Action<T1, T2>
etc. The rules for delegates are no different than the rules for other types here.
So either you need to declare one generic delegate (and use different type arguments), or use two different type names.
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