-1

I am trying to do Sum operation on a custom defined type class Percentage

public class Percentage
{
    private readonly decimal pctDecimal; //This has to be private

    public Percentage(decimal decimal_value)
    {
        this.pctDecimal = decimal_value;
    }
}

I am using an Extension method to do the sum

public static class SumExtensions
{
    public static Percentage Sum(this IEnumerable<Percentage> source)
    {
        return source.Aggregate((x, y) =>
        {
            (x + y); //I am getting Error here that "Operator '+' cannot be applied to operand of Type Percentage and Percentage."
        });
    }

}

enter image description here

Any Solution here?

John Sheedy
  • 287
  • 1
  • 8
  • 26

2 Answers2

2

You need to overload + operator. For example:

public class Percentage
{
    private readonly decimal pctDecimal; //This has to be private

    public Percentage(decimal decimal_value)
    {
        this.pctDecimal = decimal_value;
    }

    public static Percentage operator +(Percentage a, Percentage b)
        => new Percentage(a.pctDecimal + b.pctDecimal);
}
Quercus
  • 2,015
  • 1
  • 12
  • 18
0

You need to expose your decimal propery

public class Percentage
{
    private readonly decimal pctDecimal;
    public decimal PctDecimal { get {return pctDecimal;} }

    public Percentage(decimal decimal_value)
    {
        this.pctDecimal = decimal_value;
    }
}


public static class SumExtensions
{
    public static Percentage Sum(this IEnumerable<Percentage> source)
    {
        return source.Aggregate((x, y) =>
        {
            (x.PctDecimal  + y.PctDecimal );
        });
    }
}
lem2802
  • 1,152
  • 7
  • 18