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 do run it, I get the error: Use of unassigned local variable ‘ticketPrice’
As you can see it does get assigned with a value from the loop.
If I do use:
double ticketPrice = 0.0;
The error goes but then the value stays at 0.0, but I don’t understand because the messagebox comes up every time and outputs the value, so I would assume the value of tt.ticketPrice is populating ticketPrice
Can anyone help me on this matter.
Thanks
You’re saying that the value of
ticketPricestays zero, but the code doesn’t show the place where you read the value of the variable!The behavior would make sense if it was used in some code that follows the snippet that you posted. E.g.:
This doesn’t work, because the line marked as
(*)actually completes before the value of the variable is set in theCompletedhandler. To make it work, you’ll need to move the code that uses the variable into the handler (after the code that sets the variable value).Then it, of course, doesn’t make sense to declare the variable in the method, because it will be only used in the body of the lambda function, so you’ll end up with something like this:
I believe you just discovered the pain-point of asynchronous programming in C# 4 :-). That’s why F# supports asynchronous workflows (where you can write the same code witout event handlers) and why C# designers are thinking about adding similar thing to C# in the future.