I have a couple of variables that need to be assigned inside a for loop. Apparently, when the loop exits, C# ignores whatever happened in there, and the variables are returned to their original status. Specifically, I need them to be the last and next-to-last elements of a List. Here's the code:
int temp1, temp2;
for (int i = 0; i < toReturn.Count; i++) {
if (i == toReturn.Count - 2) { // Next-to-last element
temp1 = toReturn[i];
} else if (i == toReturn.Count - 1) { // Last element
temp2 = toReturn[i];
}
}
// At this point, temp1 and temp2 are treated as uninitialized
Note: Nevermind the bad variable names, they're really temporary variables. Anything more complex would confuse things.
Now, there are two ways (that I know of) to solve this: one is figuring out how to make the variables live after the loop exits, the other is to do something like in Python, where you can do temp = my_list[-1]
to get the last element of a list. Is any of these possible in C#?
Edit: When I try to compile, I get a "use of unassigned local variable 'temp1'" error. This code isn't even run, it's just sitting inside of a method that never gets called. If this helps, I'm trying to use the variables inside another loop.