I understand optional parameters, and I quite like them, but I'd just like to know a bit more about using them with an inherited interface.
Exhibit A
interface IMyInterface
{
string Get();
string Get(string str);
}
class MyClass : IMyInterface
{
public string Get(string str = null)
{
return str;
}
}
Now I would've thought that the Get
method in MyClass
inherits both of the interface's methods, but...
'MyClass' does not implement interface member 'MyInterface.Get()'
Is there a good reason for this?
Perhaps I should go about this by putting the optional parameters in the interface you say? But what about this?
Exhibit B
interface IMyInterface
{
string Get(string str= "Default");
}
class MyClass : IMyInterface
{
public string Get(string str = "A different string!")
{
return str;
}
}
And this code compiles fine. But that can't be right surely? Then with a bit more digging, I discovered this:
IMyInterface obj = new MyClass();
Console.WriteLine(obj.Get()); // writes "Default"
MyClass cls = new MyClass();
Console.WriteLine(cls.Get()); // writes "A different string!"
It would seem to be that the calling code is getting the value of the optional parameter based on the objects declared type, then passing it to the method. This, to me, seems a bit daft. Maybe optional parameters and method overloads both have their scenarios when they should be used?
My question
My calling code being passed an instance of IMyInterface
and needs to call both methods here at different points.
Will I be forced to implement the same method overload in every implementation?
public string Get()
{
return Get("Default");
}