Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cannot C# resolve the correct overload in this case?

Tags:

I've come across a strange situation which is non-ambiguous, yet the overload resolver doesn't think so. Consider:

public static class Program {     delegate int IntDel();     delegate string StringDel();      delegate void ParamIntDel(int x);     delegate void ParamStringDel(string x);      static void Test(IntDel fun) { }     static void Test(StringDel fun) { }     static void ParamTest(ParamIntDel fun) { }     static void ParamTest(ParamStringDel fun) { }      static int X() { return 42; }     static void PX(int x) { }      public static void Main(string[] args)     {         ParamTest(PX); // OK         Test(X); // Ambiguos call!     } } 

How come the call to ParamTest overloads is resolved correctly, but Test overload is ambiguous?

like image 707
Vilx- Avatar asked Feb 24 '15 13:02

Vilx-


People also ask

Why is C not A or B?

Because C comes after B The reason why the language was named “C” by its creator was that it came after B language. Back then, Bell Labs already had a programming language called “B” at their disposal.

What C++ can do that C Cannot?

On the other hand, C++ has tons of additional stuff that C can't do. Templates, polymorphism, operator overloading, etc, etc. C can mimic all of these things with different syntax, and there's no program you can write in one language that can't be written in the other language... so they're both equally capable.

Why is C used everywhere?

The C programming language doesn't seem to have an expiration date. It's closeness to the hardware, great portability and deterministic usage of resources makes it ideal for low level development for such things as operating system kernels and embedded software.

Why is C unsecure?

The top vulnerabilities found in C were buffer errors and input validation, the report reads, and although numbers have both risen and fallen since 2009, it remains the most insecure language. In C's defense, it should be noted that this is the oldest (and most widely used) programming language in the list.


1 Answers

Perhaps because https://msdn.microsoft.com/en-us/library/aa691131%28v=vs.71%29.aspx

The signature of a method specifically does not include the return type, nor does it include the params modifier that may be specified for the right-most parameter.

And the only difference between IntDel and StringDel is in the return value.

More specifically: https://msdn.microsoft.com/en-us/library/ms173171.aspx

In the context of method overloading, the signature of a method does not include the return value. But in the context of delegates, the signature does include the return value. In other words, a method must have the same return type as the delegate.

like image 86
xanatos Avatar answered Sep 20 '22 19:09

xanatos