C# operands error

112 Views Asked by At

I am trying to calculate the total for a list in my C# program, I have gotten help from several people in my class and we can't seem to find the problem, my code is,

        int totalB = 0;

        Cards.ForEach(delegate(ConsoleApplication1.Program.CreditCard Balance)
        {
            totalB= totalB + Balance;
        });

The error is this Error 1 Operator '+' cannot be applied to operands of type 'int' and 'ConsoleApplication1.Program.CreditCard'

Any help for this would be much appreciated as I have no idea and neither do the people that tried to help me with this issue

2

There are 2 best solutions below

3
On

As far as getting sum of list is concerned. it is as simple as (assuming Cards is a list)

 Cards.Sum(x=>x.YourPropertyToSum);

Your Error:

The error is this Error 1 Operator '+' cannot be applied to operands of type 'int' and 'ConsoleApplication1.Program.CreditCard'

you are trying to add an int with ConsoleApplication1.Program.CreditCard (what is this) which is obviously not a type that can be added to int. Hence the error you are getting.

3
On

I'm guessing you have a class like:

partial class CreditCard
{
    public int Balance {get; set;}
}

So following what you have, explicitly, you most likely intended:

int totalB = 0;

Cards.ForEach(delegate(ConsoleApplication1.Program.CreditCard card)
{
    totalB = totalB + card.Balance;
});

This iterates over each item in your Cards collection, and adds the value of the Balance property to totalB. Note I have called the variable card in the delegate to further illustrate what is going on - the delegate will be called once for each item in the collection. Inside, you can pick out the Balance property and add it to totalB.


Note you can also do this in a number of other ways:

  1. Using LINQ:

    int totalB = Cards.Sum(card => card.Balance);
    
  2. Using a lambda expression instead of an explicit delegate:

    int totalB = 0;
    
    Cards.Foreach(card => {totalB += card.Balance;});
    
  3. Using a foreach loop:

    int totalB = 0;
    
    foreach(CreditCard card in Cards)
        totalB += card.Balance;
    

(If you are not familiar with it, the x += y is the same as x = x + y.)