Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hey there, at first, i should say: "i'm a beginner, i'm learning"
i have a question, can i can i define string variable in "for" loop?? but i do that my program doesn't work but visual studio doesn't error, why???

What I have tried:

but i do that my program doesn't work but visual studio doesn't error, why???
Posted
Updated 17-Feb-17 22:35pm
Comments
Richard MacCutchan 18-Feb-17 4:29am    
Most likely because there is a logic error in your code, rather than a syntax error. Please edit your question and show us the code, and explain what the error is.
Karthik_Mahalingam 18-Feb-17 5:45am    
post the code that you have tried.

1 solution

You can define a string variable in the body of a for loop without problems:
C#
for (int i = 0; i < 10, i++)
   {
   string myString = i.ToString();
   ...
   }
But you can only use the string within that body - you cannot use it outside the loop as it is "out of scope" and can no longer be seen. Variables can only be used inside the "curly bracket block" within which they are declared:
C#
{ // scope of i1 starts here.
...
int i1 = 1;
...
// i2 cannot be used here.
   {  // scope of i2 starts here.
   ...
   int i2 = 2;
   ...
   } // scope of i2 ends here.
// i2 cannot be used here.
...
}  // scope of i1 ends here.


You can also define a string as the loop control variable of a for loop:
C#
for (string s = "0"; s.Length < 10; s += "0")
    {
    Console.WriteLine(s);
    }
But obviously, you can't use ++s or s++ in the "increment" section. The scope of "s" remains the same - if it not visible to code outside the loop.

For any more help, we'd need a lot more info on exactly what code you have written!
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900