4

Possible Duplicate:
C# 4: conflicting overloaded methods with optional parameters

I just have one small research and created next code.

namespace Test {
class Program
{
    public interface ITestA
    {
        void MethodA(int a, int b);
    }

    public class TestAClass : ITestA
    {
        public void MethodA(int a, int b)
        {
            Console.WriteLine("MethodA with param");
        }

        public void MethodA(int a, int b, bool logic = true)
        {
            Console.WriteLine("MethodA logic with param");
        }
    }

    public interface ITestB
    {
        void MethodA(int a, int b, bool logic = true);
    }

    public class TestBClass : ITestB
    {
        public void MethodA(int a, int b)
        {
            Console.WriteLine("MethodB with param");
        }         

        public void MethodA(int a, int b, bool logic = true)
        {
            Console.WriteLine("MethodB logic with param");
        }
    }

    static void Main(string[] args)
    {
        var testA = new TestAClass();
        testA.MethodA(1, 1);            
        var testB = new TestBClass();
        testB.MethodA(1, 1);   
    }
} }

I have a question why compiler always choose short method with 2 parameters. And of course all this work by the same way and without Interface.

Thanks

Community
  • 1
  • 1
Arbejdsglæde
  • 13,670
  • 26
  • 78
  • 144
  • 3
    So if it works the same way with and without the interface, why show the interface in your question? The idea is to use the *minimal* amount of code needed to reproduce the behavior. That keeps us focused on the actual question, rather than irrelevant details. – Cody Gray - on strike May 16 '11 at 12:25
  • 2
    Also, this is most certainly **not** operator overloading, but rather *method* overloading, a completely different thing. – Cody Gray - on strike May 16 '11 at 12:25
  • 2
    And the main issue is with optional parameters, not interfaces. – Rik May 16 '11 at 12:29
  • If these sorts of topics interest you, you might want to check out my blog this week. I'm running a series on how interfaces and optional argument declarations work in C#. – Eric Lippert May 16 '11 at 14:17

2 Answers2

3

This boils down to how the compiler treats named and optional parameters.
Check out this article at MSDN for more information, especially the paragraph Overload Resolution.

If two candidates are judged to be equally good, preference goes to a candidate that does not have optional parameters for which arguments were omitted in the call. This is a consequence of a general preference in overload resolution for candidates that have fewer parameters.

This is why in your case the compiler chooses the method without any optional parameters.

Jakob Möllås
  • 4,239
  • 3
  • 33
  • 61
1

Because compiler finds a method that correspond perfectly to calling method and use that.
Compiler searches for other suitable methods if first way fails...

Marco
  • 56,740
  • 14
  • 129
  • 152