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?
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With