Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Delegate Duplicate Definition - Why?

I have two generic delegates that I am atttempting to define that the compiler is complaining that they are duplicates, but to my eye are completely different. What am I doing/understanding wrong?

delegate TReturn foo<TParameter, out TReturn>(TParameter parameter, IItem item);

and

delegate TReturn foo<TParameter, out TReturn>(TParameter parameter, int field, IItem item);

If I add a new generic parameter to the second delegate, everything works.

delegate TReturn foo<TParameter, TField, out TReturn>(TParameter parameter, TField field, IItem item) where TField struct

but that is does not appear to be correct. I will always be passing an int for field - it should not be a generic.

like image 461
David Williams Avatar asked Feb 20 '23 23:02

David Williams


2 Answers

Delegates are not methods. They know how to call a method, but they themselves are not methods (a delegate is an object) and can therefore not be overloaded like a method.

See this post for an explanation of why it cannot be possible.

like image 195
Kevin Aenmey Avatar answered Feb 22 '23 12:02

Kevin Aenmey


When using delegate keyword, what happens behind the scenes is that the compiler generates a class based on its definition. So when you define a delegate like this:

delegate TReturn foo<TParameter, out TReturn>(TParameter parameter, IItem item);

a following class is generated from it:

class foo<TParameter, out TReturn> : MulticastDelegate
{
    public void Invoke(TParameter parameter, IItem item) { ... }
    ....
}

As you can see, when you have two delegates with the same name and same generic parameters, it results in generation of two identical classes, which is, of course, not acceptable.

I recommend an excellent book CLR via C# from Jeffrey Richter that sheds more light on behind-the-scenes stuff like this - and much more.

like image 31
Nikola Anusev Avatar answered Feb 22 '23 12:02

Nikola Anusev