开发者

About using variable inside of nested if

if(){
      String var=1; 
      if(var==-1){
        //do this
      }
      else
      {
         if()
         {        
           String myString=var; //This is where I want to use var
         }
      }
}

Now myString is not getting assigned the value of var..why is that ? It's nested if..it should get the value..isn'开发者_StackOverflowt it ?


Following code seems to work fine:

if (true)
{
    String var = "1";
    if (var == "-1") {/*DoSomething()*/ }
    else
    {
        if (true)
        {
            String myString = var; //Gives 1 in myString!
            MessageBox.Show(myString);
        }
    }
}

Variable and Method Scope in Microsoft .NET is a good reference to understand how scoping works.

Btw, var is a type used in 3.5 and above; should avoid naming variables akin to type names.


Your question is vague and.. unhelpful, but perhaps you should just remember:

int n;
if (true) {
  // you can access/change n from here no problem
  int f;
} else {
  // can't access f here, if that answers your question
}
//you cannot access f, it no longer exists.

To put it bluntly, anything outside the { } that a variable was declared, would not know about it (even without a condition/loop). Anything inside will.


myString must get the value of var. if not, check your if conditions.


disregarding all syntax mistakes,
assuming whatever is in the bottom "if" evaluates to "true", and that var is not equal to -1 (you really should put a breakpoint there, and see if the debugger ever reaches that assignment). myString will get var's value. Notice however, that once out of the block (just after the next "}") myString doest not longer exists.
Also notice all syntax mistakes (using "var" which is a keyword, assigning an int to string...)


In general, when you declare a variable, its accessible in the scop which is defined in...
In your example, var (u cant use this name because this is a reserved word in VS2008) is accesible in all other if blocks couse those are in that scop.


Take care of keywords in C# language (and other) :)


Apart from avoiding keywords, the only thing I can immediately see wrong with getting var assigned as myString's value is that your example literal isn't double-quoted. (I'm assuming you're not having issues with myString getting destroyed before you access it given you're saying that it's not returning the same value as var. If you're trying to access myString from outside the if that you initialise it in, you need to initialise it less locally than you currently are)

String literals need to be inside double-quotes to function correctly, so check if var is correctly assigned to 1 in your base program. If that's not it, and you've got correct scope on myString, you're going to need to post your actual code rather than pseudocode, because it's hard to catch your error here otherwise.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜