I use interface type when I create object some class - should I set default value for parameter (=5) only in interface method as You can see below? Or maybe also set default value (=5) also in class method - what is the best approach IN THAT CASE?
public interface MyInterface
{
void MyMethod(int count = 5);
}
public class MyClass : MyInterface
{
public void MyMethod(int count)
{
}
}
public class TestClass
{
private MyInterface _x;
public TestClass(MyInterface x)
{
_x = x;
}
public void TestMethod()
{
_x.MyMethod();
}
}
You'd need to define "best". The default value is basically only applied to whichever type you try to call against. So for example, with your current code:
MyClass c = new MyClass();
c.MyMethod(); // Invalid
MyInterface i = new MyClass();
i.MyMethod(); // Valid
If you only ever refer to the class via the interface - or if that's the only way in which you ever call the method, at least - then it's fine to put the default just in the interface.
You could even give different default parameter values for the class and the interface - but I'd strongly recommend against doing that. That also means that if you do decide to use the same default value for both the class and the interface, you need to make sure that you keep them in sync if you ever (carefully) change one of them.
Personally I use optional parameters pretty sparingly. They can be very useful, but you need to think carefully about them. An alternative would be to declare two overloads in the interface:
void MyMethod();
void MyMethod(int x);
... and either have an abstract class which implements the interface, keeping MyMethod(int x)
abstract but calling it directly from MyMethod()
with a default value, or simply implementing it appropriately in MyClass
.
Fundamentally you want to work out what behaviour you want - it's probably easy enough to code up any behaviour you want, when you've worked out what that behaviour is.
See more on this question at Stackoverflow