I want to find the sum of a simple list. But I can’t create a method Sum() without arguments. Please suggest possible solutions.
void Main()
{
var chain1 = new Add(5)).Append(new Add(10)).Append(new add(15));
var sum = chain.Sum();
}
public abstract class Strategy
{
private Strategy _next;
public Strategy Append(Strategy next)
{
if(_next == null){
_next = next;
} else {
_next.Append(next);
}
return this;
}
}
public class Add : Strategy
{
int _num;
public Add(int num) => _num = num;
public int Sum()
{
....
}
}
>Solution :
@marsze is correct, there are much better ways of doing this… but I was able to modify it a bit and ended up with this non battle hardened code:
public abstract class Strategy
{
protected Strategy _next;
public Strategy Append(Strategy next)
{
if (_next == null)
{
_next = next;
}
else
{
_next.Append(next);
}
return this;
}
public abstract int Sum();
}
public class Add : Strategy
{
int _num;
public Add(int num) => _num = num;
public override int Sum()
{
if (_next == null)
{
return _num;
}
return _num + _next.Sum();
}
}