Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top