Home > Mobile >  Use of unassigned local variable that does not exist in current context
Use of unassigned local variable that does not exist in current context

Time:11-01

I am trying to add the concessionItem price to a list. I can not access the variable after the for loop is finished, because it is out of scope. I've tried writing totalCost above the foreach loop as well, but then it is not accessible within the logic.

public void PayForConcessions()
        {
            foreach (ConcessionItem ci in concessionItems)
            {
                decimal totalCost;
                totalCost  = ci.Price;
            }

            this.RemoveMoney(totalCost);
        }

CodePudding user response:

you have to assign totalCost and move it before foreach loop

        decimal totalCost = 0m;
       foreach (ConcessionItem ci in concessionItems)
            {
              
                totalCost  = ci.Price;
            }

CodePudding user response:

I've tried writing totalCost above the foreach loop as well,

I think you might have put it in the wrong place.. This should be fine:

    public void PayForConcessions()
    {
        decimal totalCost = 0;
        foreach (ConcessionItem ci in concessionItems)
        {
            totalCost  = ci.Price;
        }
        this.RemoveMoney(totalCost);
    }

Basic rule of variable scoping; inside the same set of { } brackets, or any nested brackets within, below the point of declaration..

CodePudding user response:

You can try using Linq and get rid of loop at all:

using System.Linq;

...

public void PayForConcessions() => 
  RemoveMoney(concessionItems.Sum(ci => ci.Price));

CodePudding user response:

decimal total cost; needs to be declared inside the method body, but above the loop:

public void PayForConcessions()
{
    // HERE
    decimal totalCost = 0;

    foreach (...)
    {
        ...
    }
}

For the "use of unassigned local variable", you just need to assign the default value. So decimal totalCost = 0;

  •  Tags:  
  • c#
  • Related