This question already has answers here:
C# The name ' ... ' doesn't exist in the current context
(2 answers)
The name 'input' does not exist in the current context
(4 answers)
The name does not exist in the current context when using an if statement [duplicate]
(1 answer)
Variable does not exist in the current context?
(6 answers)
the name door does not exist in the current context
(4 answers)
Closed 1 year ago.
yes i know there is a bunch of other threads with likely the same question... but i still dont get it.
I'm writing in C# via Visual Studio and want to make something like an menu so you can choose different options... dependind on which option you choose, the variable will change.
But it's important to have only one variable, so the variable will change when the user is chooses an option.
Something like this:
stt:
string m = Console.ReadLine();
Console.Clear();
int c = Convert.ToInt32(m);
if (c == 1)
{
var ttt = "one";
}
if (c == 2)
{
var ttt = "two";
}
else {
goto stt;
}
Console.WriteLine("" + ttt);
Console.ReadKey();
I always get the error
The name 'ttt' does not exist in the current context
So I have to declare the var outside the if statement... but how??
By writing..
string ttt;
..above the first if. You can't write var ttt; above the if, because it doesn't declare the type (and you're not providing a value so the compiler cannot infer the type), so you have to give the type (string) when you declare the name
If you do this you'll have to remove the vars inside the ifs (but leave eg ttt = "one") so you don't end up declaring another variable with the same name
The quick of it is:
stt:
string m = Console.ReadLine();
string ttt;
Console.Clear();
int c = Convert.ToInt32(m);
if (c == 1)
{
ttt = "one";
}
if (c == 2)
{
ttt = "two";
}
else
{
goto stt;
}
Console.WriteLine("" + ttt);
Console.ReadKey();
Why? Concept called variable scopes. In your sample, ttt was only created inside the if statement, or the else statement, and therefore would not live beyond the scope of that statement. In order to address ttt outside of those limited scopes, it had to be declared higher up.
Off topic - goto. Please try to use loops or conditionals.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
this might be a rather stupid question, but im new to this codeing thing. I was wondering if you can take a variable from an if statement and use it outside the if statement as I showed in this exemple down here:
bool ex = true;
if (ex == true)
{
int num = 10;
}
Console.WriteLine(num);
I already tried to declare the variable before the if statement but i gave me an error:
You can declare a variable before if statement and then you can bind a new value to that variable inside if statement and use it outside if statement wherever you required inside your function scope.
bool ex = true;
int num = 0;
if (ex == true)
{
num = 10;
}
Console.WriteLine(num);
Note that i have not used int keyword again while binding value to num variable in if statement as we have defined it already outside of the loop otherwise it will give an error like -> A local variable named 'num' cannot be declared in this scope because it would give a different meaning to 'num'.
Above the if statement write, "
int num;
"
and then inside the if statement write, "
num = 10;
"
You don't have to initialize a variable when you declare it.
The conceptual thing this example teaches is that of local variable scopes.
The body of a method (e.g., Main) is surrounded by { and } characters. This indicates that any variables you declare between these braces can only be written or read to from within the same braces. We call this a "scope". And this applies to most cases of { and } characters, nested within the method.
So in your case:
static void Main()
{ // beginning of method scope
bool ex = true;
if (ex == true)
{ // beginning of if statement scope
int num = 10;
} // end of if statement scope
Console.WriteLine(num);
} // end of method scope
There are two scopes: a scope for the Main method, and a scope within that first scope just for the code inside the { and } after the if.
ex is declared (bool ex) in the outer scope, so you can use it anywhere in the method, including within the inner scope.
num is declared (int num) in the inner scope, so you can only use it within the inner scope, not the outer scope.
To fix this, you can declare a variable, then later assign a value to it. So our next shot would be:
static void Main()
{
bool ex = true;
int num; // declare the variable here
if (ex == true)
{
num = 10; // assign the variable here
}
Console.WriteLine(num);
}
This is closer, but we still get an error, this time:
CS0165 Use of unassigned local variable 'num'
That's because of another rule: in order to use a local variable, the compiler has to be able to know that the variable has always been assigned a value before it's used. In this case, what would happen if ex was false? Then we would declare num, but never give it a value, because the program wouldn't enter into the if scope.
The solution is to give num a value, either at the same time we declare it...
static void Main()
{
bool ex = true;
int num = 5; // declare and assign the variable here
if (ex == true)
{
num = 10; // re-assign the variable here
}
Console.WriteLine(num);
}
...or in an else statement.
static void Main()
{
bool ex = true;
int num; // declare the variable here
if (ex == true)
{
num = 10; // assign the variable here if ex is true
}
else
{
num = 5; // assign the variable here if ex is false
}
Console.WriteLine(num);
}
In the first case, num is given a value as soon as we declare it, so even if we don't enter the if block, num will have a value when we reach Console.WriteLine.
In the second case, the compiler knows that when you chain if and else together, the program is going to go into exactly one of the two. Thus, if we ensure both paths set num, then it will also be guaranteed to have a value once we reach Console.WriteLine.
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.
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
}
This question already has answers here:
Variable declaration in a C# switch statement [duplicate]
(7 answers)
odd variable scope in switch statement
(4 answers)
Closed 9 years ago.
So if I have a switch with 3 cases, each case has duplicate local variables declared in them. You would think that the variables would be local to that case so you should be able to use the same name repeatedly. However, this doesn't appear to be the 'case'.
Apparently the other case blocks can see the variables in each other.
Okay, no big deal right? Except that when you try and access that variable that it can obviously see, it says it can't see it???
int index = list.SelectedIndex;
switch(index){
case(0):
bool val = true; //First declaration s'allll good
if(val) //No issues here either obviously
MessageBox.Show("Huh?");
break;
case(1):
bool val = true; //Says it already exists??
if(val)
MessageBox.Show("Huh?");
break;
case(2):
bool val3 = true; //Change the variable name so you can use it however,
if(val) //When you try to access the val in case 0 it says it doesn't exist?????
MessageBox.Show("Huh?");
break;
}
Is there an obvious syntax fold in space time I am missing here?
The variables, in the IL, are defined to the scope of the switch, so you can't reuse them in the other case statements because it would redefine them.
Likewise, you still have to define the variables for each case (i.e. you've seen how even if one case has the variable the others can't actually leverage its definition).
The better approach, for you, is to define val outside the switch.
Since cases are just labels, there's no scoping between cases -- they can see variables on the highest scope of the case, hence collisions on your val.
You can either move bool val outside of the switch, or you can enclose the cases in braces to scope it yourself, i.e.
case(0):
{
bool val = true;
if (val)
MessageBox.Show("Huh?");
}
break;
Variables in a switch statement are scoped to the entire switch statement. See this MSDN page at the bottom "The scope of a local variable or constant declared in a switch block is the switch block.".
To get around this, you can either declare the variable above the switch statement or (less cleanly) declare it a single time and re-use throughout the switch statement like so.
int index = list.SelectedIndex;
switch(index){
case(0):
bool val = true; //First declaration s'allll good
if(val) //No issues here either obviously
MessageBox.Show("Huh?");
break;
case(1):
val = true; //Declared in case 0
if(val)
MessageBox.Show("Huh?");
break;
case(2):
val = true; //Still declared from case 0
if(val)
MessageBox.Show("Huh?");
break;
}
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.