Access variable inside while loop from outside (C#)?
15,498
Solution 1
Declare MAX before you start the while loop. The way you have it you can only access within the while.
Double MAX = 0;
while (Condition)
{
MAX = somecode.....
.....
}
Console.WriteLine("The OPTIMAL Value : " + MAX);
Solution 2
You must declare the variable BEFORE the loop.
Double MAX;
while (Condition)
{
MAX = somecode....
}
Console.WriteLine("The OPTIMAL Value : " + MAX);
Solution 3
It would seem the underlying problem is understanding how scope works. A google search for "C# how scope works" (or similar) might prove helpful.
I found one that's quite simple and easy to understand: http://www.codecandle.com/Articles/191/Csharp/Variables/Variable-scope/codedetail.aspx
So as many others have mentioned you'll need to declare your variable outside your inner scope in order to have access to the changes.
Some pseudo code
// declare variable;
{
// change variable;
}
// use changed variable
Comments
-
Jimey1000 over 1 year
I'm New to C# and I'm trying to reach the value of MAX from the while so i can use it outside but i can't...anyone have some ideas !!! Thanks In Advance
while (Condition) { Double MAX = somecode..... ..... } Console.WriteLine("The OPTIMAL Value : " + MAX);
-
Jimey1000 over 10 yearswhat if i want to make change to the value of MAX inside the while loop ,the changes wont apply to the value !
-
Alex S. over 10 yearsNot really sure what you mean. If you change the value of MAX inside of the while loop, and then reference it after the loop, the value you set inside of the while is valid outside as well, as long as you've declared is before entering the while.
-
Parziphal over 8 yearsRemember to declare and set a value to it. If you just do
Double Max;
you will still get theUse of unassigned local variable
error. (sorry if this obvious, but I had problems with this) -
Mustafa Demir almost 6 yearsSir I wanna add my datum to datagrid in another class(Page) that datum in while. Could you give me any idea to do that ?My While Loop Thank you so much