Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When interface method has no parameters why isn't the implementation recognised of a method with all optional parameters?

I've been playing around with optional parameters and came accross the following scenario.

If I have a method on my class where all the parameters are optional I can write the following code:

public class Test
{
    public int A(int foo = 7, int bar = 6)
    {
        return foo*bar;
    }
}
public class TestRunner
{
    public void B()
    {
        Test test = new Test();
        Console.WriteLine(test.A()); // this recognises I can call A() with no parameters
    }
}

If I then create an interface such as:

public interface IAInterface
    {
        int A();
    }

If I make the Test class implement this interface then it won't compile as it says interface member A() from IAInterface isn't implement. Why is it that the interface implementation not resolved as being the method with all optional parameters?

like image 508
John Pappin Avatar asked Jul 14 '11 08:07

John Pappin


2 Answers

These are two different methods. One with two parameters, one with zero. Optional parameters are just syntactic sugar. Your method B will be compiled to the following:

public void B()
{
    Test test = new Test();
    Console.WriteLine(test.A(7, 6));
}

You can verify this by looking at the generated IL code.

like image 94
Daniel Hilgarth Avatar answered Sep 23 '22 16:09

Daniel Hilgarth


You may want to read the four part series of blog posts by Eric Lippert on the subject. It shows such corner cases and will allow you to understand why those are actually different methods.

http://ericlippert.com/2011/05/09/optional-argument-corner-cases-part-one/

like image 24
Lucero Avatar answered Sep 24 '22 16:09

Lucero