Method Overloading and Default Parameters, any other option in Delphi ?

delphi

Solution

You should use an open array:

function Sum(const Values: array of Integer): Integer;
var
  i: Integer;
begin
  Result := 0;
  for i := low(Values) to high(Values) do
    Result := Result + Values[i];
  end;
end;

And call it like this, using an open array constructor:

x := Sum([1, 2]);
y := Sum([1, 2, 3]);
z := Sum([42, 666, 29, 1, 2, 3]);
i := Sum([x, y, z]);

and so on.

In fact, you'll find this very function (names `SumInt` for the integer version), and many similar, already implemented in the `Math` unit.

Problem

I get a set numbers like A, B, C, D in my program , sometimes I need to calc the sum of several of theses numbers like : ``` function DoIt2 (a, b : Integer) : Integer ; overload begin result := a +b ; end; function DoIt3 (a, b, c : Integer) : Integer ; overload begin result := a +b +c ; end; ``` there are many DoIt's function involved in my problem. I can not use e.g. a IntegerList as I need to Know what has been A and B and so on ..... Any good solution compared to endless function overloading ?

Original source