Using an unassigned local variable? WITH#

I have the following code:

        double ticketPrice;
        LoadOperation loGetTickets = ticketClass.loadTickets();
        loGetTickets.Completed += (s, args) =>
        {
            foreach (Web.Ticket tt in ticketClass.getContext())
            {
                if (tt.bookingId == data.bookingId)
                {
                    pView.lblTicketAmount.Content = "Β£" + tt.ticketPrice;
                    MessageBox.Show("Price: " + tt.ticketPrice);
                    ticketPrice = Convert.ToDouble(tt.ticketPrice);
                    pView.lblTicketName.Content = tt.ticketName;
                    break;
                }
            }
        }; double subTotal = ticketPrice + ticketQuantity;

When I run it, I get an error: Using the unassigned local variable 'ticketPrice'

As you can see, it is assigned a value from the loop.

If I use:

double ticketPrice = 0.0;

Error, but then the value remains in 0.0, but I do not understand, because the message box appears every time and displays the value, so I would assume that the value is tt.ticketPricefilledticketPrice

Can anyone help me on this.

thank

+3
source share
4 answers

You say that the value ticketPriceremains zero, but the code does not show the place where you read the value of the variable!

, , , . :.

double ticketPrice;        
LoadOperation loGetTickets = ticketClass.loadTickets();        
loGetTickets.Completed += (s, args) =>  { 
  // Set value of 'ticketPrice'
  ticketPrice = ...
};

// Use the value of the variable
Console.WriteLine(ticketPrice); // (*)

, , (*), , Completed. , , , ( , ).

, , , -, - :

LoadOperation loGetTickets = ticketClass.loadTickets();        
loGetTickets.Completed += (s, args) =>  { 
  double ticketPrice;        
  // Set value of 'ticketPrice'
  ticketPrice = ...

  // Use the value of the variable
  Console.WriteLine(ticketPrice); // (*)
};

, # 4:-). F # ( witout ) # # .

+3

ticketPrice , . ( ), , , .

+1

double ticketPrive; foreach, .

0

, .

, , , .

If you try to use a variable immediately, it will not be set. You cannot use a variable until an event occurs. The easiest way to do this is to put code that uses a variable inside an event handler.

0
source

All Articles