How to avoid duplicate optional arguments in overloads?

47 Views Asked by At

In C#, I have a function of the form

void Foo(Vector<double> v, int k = 1)
{ ... }

where Vector<double> is a type from the MathNet.Numerics.LinearAlgebra package which represents a mathematical column vector. Semantically, it would make a lot of sense to be able to call this method with a double in place of the vector, so that the caller does not have to cast a scalar to a 1D vector in the 1D case. Hence I have also made an overload of the following form:

void Foo(double d, int k = 1) => Foo(d.ToVector(), k);

(ToVector is an extension method.) The problem with this is that the default value k = 1 must be added in both signatures. Thus, if I ever want to change the default value, I must remember to do it in two places. A possible solution could be to replace the overload with the following two:

void Foo(double d) => Foo(d.ToVector());
void Foo(double d, int k) => Foo(d.ToVector(), k);

But what if I had not one, but N optional arguments? With this solution I would then need 2^N overloads.

Is there a better way?

1

There are 1 best solutions below

0
shingo On BEST ANSWER

You can define a constant as the default value, this way, you only need to maintain this constant.

public const int DefaultK = 1;

void Foo(Vector<double> v, int k = DefaultK)
{ ... }

void Foo(double d, int k = DefaultK)
{ ... }