Access the value of a variable outside its scope [duplicate] - c#

This question already has answers here:
Access variable inside while loop from outside (C#)?
(4 answers)
Closed 2 years ago.
I am new to C# and trying to automate a window app using appium .I have the following code
int i = -1;
foreach (var row in SummaryTableRows)
{
i++;
//Console.WriteLine(row.Text);
if ((row.Text.Contains("cheq")) && (row.Text.Contains("acitve")))
{
var DemandData = FirstRow.Split(new[] { " " },
StringSplitOptions.RemoveEmptyEntries);
string Sub = DemandData[1];
string Type = DemandData[0];
bFlag = true;
break;
}
}
buttonBar.ExitFormBtn.Click();
buttonBar = null;
//Should be back to member form
SubCheq.SendKeys(Sub + Keys.Tab);
I want to access the value of Sub and Type outside the if loop. In vb script it was never an issue but seems like in C# the scope of the variable is limited to the foreach block. So My question how can I access the value of Sub and Type.

You can not access a variable outside of it's scope. The scope literally means "where you can access the variable". So you want to accesss the values, where you can not access the values. At wich point you can access the variable there, and that is it's new scope.
What you can do is change the scope. If you want a variable avalible outside a specific block, declare it outside of that block. Just declare sub (and propably type) outside the loop. Then only set the values insdie it, with every loop.
I am unsure why you even ask, as you already do that with i: int i = -1; is a declaration with initialisation. And i++; is jsut shorthad for i=i+1;, so you re-assing it every loop (the new value just happens to be close to the ol one). Strings you many want to initialize with null or maybe a empty string, depending on what you do with it later/how you check for 0 itterations of the foreach loop.

Related

How to interact with boolean variables inside of if statements and outside of them. C# [duplicate]

This question already has answers here:
Access variable inside while loop from outside (C#)?
(4 answers)
how to use a variable outside of an if statement that is already declared inside an if statement
(2 answers)
Closed 2 years ago.
I am trying to assign a bool variable if it is true or false according to a if statement. But after that I want to use the same variable outside of the if statement for a different if statement and use it as a condition. Is there any way to interact with the bool created inside of an if statement also outside of the if statement? It is written in C#.
This is an example:
string enteredPassword = Console.ReadLine();
if (enteredPassword == "magic")
{
bool passwordIsValid = true;
}
else
{
bool passwordIsValid = false;
}
if (passwordIsValid)
{
Console.WriteLine("Access Granted!");
}
else
{
Console.WriteLine("Access Denied!");
}
I want to use variable passwordIsValid to determine if the if function should be triggered or moved on to else. Thanks

For loop never satisfies a condition [duplicate]

This question already has answers here:
Static vs non-static class members
(7 answers)
Closed 4 years ago.
In the current page (which is contained inside a frame inside MainWindow) I have this happen when I click a button:
for (int i = 0; i < mw.pizzas.Length + 1; i++)
{
if (i == 10)
{
MessageBoxResult result = MessageBox.Show("You can't order more than 10 pizzas");
break;
}
if (mw.pizzas[i] == null)
{
mw.pizzas[i] = pizza;
break;
}
}
NavigationService.Content = new AnotherPage();
The mw.pizzas string array contains 10 (I think undefined) variables. I have defined it in MainWindow:
public string[] pizzas = new string[10];
I have defined it on the current page, like so:
MainWindow mw = new MainWindow();
This loop increments by defining these 10 slots with the contents of the variable "pizza". When all of the indexes of the array are defined, a message should pop up. However, this message never shows up. What am I doing wrong here?
Edit: This is just a wild guess. It might have to do with me creating a new CurrentPage every time this page is navigated to. Every time one of these indexes is defined, this navigates back to the previous page, then uses NavigationService.Content = new CurrentPage();
Edit 2: Looks like there is something wrong with the second statement. mw.pizzas[0] is null, then gets the contents of pizza in it, then somehow goes back to being null after the program exits the page and enters it once again.
Edit 3: I tried to make the pizzaIDs array static, but I get the following error: Member 'MainWindow.pizzaIDs' cannot be accessed with an instance reference; qualify it with a type name instead
You loop goes from 0 to 9 inclusive, the array indicies, when it hits 10, it breaks out of the loop and doesn't execute.

C# : error using if/switch : "Local variable already defined in this scope" [duplicate]

This question already has answers here:
C# declare variable into if statement
(4 answers)
Closed 8 years ago.
I'm new to C# and my problem is probably simple, but I don't get it:
I need to assign some values to an array depending on a condition.
So I can use "if" of "switch" statement for checking the condition.
However,if I use "switch" then I get an error "Local variable already defined in this scope".
And if I use "if" then I get an error "does not exist in current context"
Example:
int x;
x=1;
//1:
//a) does work...
if (x==1)
{
string[,] arraySpielfeld2d =
{
{"1", "1" },
{"1", "1" }
};
}
else
{
string[,] arraySpielfeld2d =
{
{"1", "1" },
{"1", "1" }
};
}
//b) but this does not work
MessageBox.Show(arraySpielfeld2d[0,0]); //error: does not exist in current context
//2) doesn't work at all
switch (x)
{
case 1:
string[,] arraySpielfeld2d =
{
{"1", "1" },
{"1", "1" }
};
break;
case 2:
string[,] arraySpielfeld2d = //error:Local variable already defined in this scope
{
{"2", "2" },
{"2", "2" }
};
break;
}
So using "if" I can at least populate the array (1a)...but I can not access the array elements (1b)...
Using "switch" doesn't work at all.
So how could I assign and then access values to an array depending on a condition (if/switch)?
I use Visual Studio 2010.
thanks
What you're encountering here is the scope of the variables.
Any variable declared inside a block { } is only visible within that block. Any code after the block will not be able to see it. Thus, your if-using code declares the variable, but it does so inside those two branches so the code immediately afterwards can't see it at all.
The solution is to declare the variable before the if, assign it in the blocks, then you can use it afterwards (just make sure you don't leave a path where it can end up unassigned, unless you're prepared for that possibility when you use it).
The switch code doesn't work because there's only one block for the whole statement, and you declare the same variable name twice within it.
It still has the same scoping problem though, because that variable won't be visible outside the switch block. Again, the solution is to declare the variable first, then assign it within the switch.
You have declared the array in the scope of the if, but you want to access it from outside. That doesn't work. You have to declare it outside. But then you can't use the collection initializer syntax:
int x;
x=1;
string[,] arraySpielfeld2d = new string[2,2];
if (x == 1)
{
arraySpielfeld2d[0,0] = "1";
arraySpielfeld2d[0,1] = "1";
arraySpielfeld2d[1,0] = "1";
arraySpielfeld2d[1,1] = "1";
}
else if(x == 2)
{
arraySpielfeld2d[0, 0] = "2";
arraySpielfeld2d[0, 1] = "2";
arraySpielfeld2d[1, 0] = "2";
arraySpielfeld2d[1, 1] = "2";
}
MessageBox.Show(arraySpielfeld2d[0,0]);
The same is true for a switch which also creates a new scope if you use braces({ }).
Note that you don't need an if or switch in this case, it seems that you always want to use x:
string val = x.ToString();
string[,] arraySpielfeld2d =
{
{val, val },
{val, val }
};
declare arraySpielfeld2d outside the if/else or switch scope then you can access it outside if/else and inside switch
Here is how your code should start, basically you locked up the scope of the variable inside the if-then-else, it needs to be declared outside of the brackets.
int x;
x=1;
// define variable OUTSIDE of the if-then-else scope
string[,] arraySpielfeld2;
or
string[2,2] arraySpielfeld2 = new string[2,2]();
if (x==1)
{
// assign the variable here if you create it then scope is
// restricted to the code between if-then-else
// unlike javascript you can't define a global
// variable here (by leaving off the var part)
arraySpielfeld2d = ... snipped
}

On Scope of Variables in .NET(c#) [duplicate]

This question already has answers here:
Variable scope confusion in C#
(4 answers)
Closed 9 years ago.
Reference Code
public void MyMethod()
{
string x;
List sampleList = populateList();
foreach(MyType myType in sampleList)
{
string x; // why is this not allowed?
doSomethingwithX(x);
}
}
I recently started learning C# and today ran into issue with code similar to the above. VS2010 flagged the commented code with this message a local variable named x cannot be declared in this scope because it would give a different meaning to variable x which is already used in parent or current scope to denote something else....
I dont get it...isnt that the whole essence of block statements and scoping...I know i can just change my variable names and go ahead.but i'd like to know WHY?
I dont get it...isnt that the whole essence of block statements and scoping...
No, not really. The intention of scoping isn't "to allow you to reuse names".
I know i can just change my variable names and go ahead.but i'd like to know WHY?
It reduces the possibilities for confusing code, basically. There are various situations where C# prevents you from writing code which is confusing. Not as many as we might like, of course, but where there's no clear benefit from allowing something, and a clear benefit from disallowing it, it makes sense to disallow it.
Would you ever want to work with code that had the same local variable name in scope twice? Wouldn't you always prefer the original developer to use a different name? I would - so I'm glad the compiler enforces that.
Note that this doesn't prevent the same local variable name being used twice in the same method - they just can't be in the same scope. So this is valid:
public void Foo()
{
{
int x = 10;
...
}
{
int x = 10;
...
}
}
But this isn't:
public void Foo()
{
{
int x = 10;
...
}
int x = 10;
...
}
If the second example is confusing, you need to bear in mind that the scope of a local variable is the block in which it was declared - not from the declaration point onwards.
Previously defined x is still in scope that's why compiler stops you from declaring other one.
You can verify this by limiting the scope of previous variable by wrapping it in curly braces -
public void MyMethod()
{
{
string x;
}
List sampleList = populateList();
foreach(MyType myType in sampleList)
{
string x; // This will be fine.
doSomethingwithX(x);
}
}
The x in the for loop is not visible outwith the loop, but the x you declared at the start of the method is visible within the for loop.
Outwith the loop you have one x but inside it there are two, both of which are being declared
You cannot declare string x; again. .. it will have different meaning. Since string x; is declared inside a method. The scope of x will be available through out the method. . So please declare some other variable inside for each loop. ..
Or you can just x. Instead of declaring again. .

Why c# compiler generates a compile error? [duplicate]

This question already has answers here:
Why can't a duplicate variable name be declared in a nested local scope?
(9 answers)
Closed 9 years ago.
I have following code
using(some code)
{
var b = ....
}
var b = ...
Erorr: A local variable named 'b' cannot be declared in this scope because it would give a different meaning to 'b', which is already used in a 'child' scope to denote something else
Ok, editing
using(some code)
{
var b = ....
}
b = ...
Error: The name 'b' does not exist in the current context
"The local variable declaration space of a block includes any nested blocks. Thus, within a nested block it is not possible to declare a local variable with the same name as a local variable in an enclosing block." Variable Scopes, MSDN
can you do this?
for (int i = 0; i < 10; i++)
{
int j = 1;
}
int j = 2;
The answer is NO which means it pretty much consistent everywhere. Now it begs the question why. Answer to this question is It is illegal to have two local variables of the same name in the same local variable declaration space or nested local variable declaration spaces. And in the above case declaration of J is within the same nested scope.
The correct code should be:
var b = something;
using(some code)
{
b = smth;
}
b = smth;
You cannot use a variable declared inside a block ({}) outside of that block.

Categories