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
Bwill be compiled to the following:You can verify this by looking at the generated IL code.