Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I define 2 delegates with the same name but different parameters?

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.

like image 969
Raheel Khan Avatar asked Jun 10 '13 16:06

Raheel Khan


People also ask

Is it possible to define two methods with the same name and arguments but with a different return types C#?

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.

Can we pass delegate as parameter?

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.

How many methods can be called using a delegate?

Only one method can be called using a delegate.

Can a delegate point to more than 1 method?

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.


1 Answers

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.

like image 183
Jon Skeet Avatar answered Sep 19 '22 12:09

Jon Skeet