Click here to Skip to main content
15,888,527 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi
Basically i have a if loop selection, and i have defined a variable in it, however in the else i wish to use it aswell, but i cant does anyone have any suggestions how i can do this please.

SQL
if (Selection)
{
String Name = "Hello";
}
Else
{
Name;
}


Above is what i wish to happen something like that bu it wont let me use the variable "Name" any suggestions please.
Posted

C#
String Name = string.Empty;

if (Selection)
{
Name = "Hello";
}
Else
{
Name = "Another value";
}
 
Share this answer
 
Just declare your varable outside of if block.

C#
String Name;
if (Selection)
{
Name = "Hello";
}
else
{
Name="Something else";
}
 
Share this answer
 
v2
Comments
Member 9665875 9-Dec-13 13:40pm    
your the master, with a plan :)
The only problem is the locality of definition: your declaration of Name is accessible only in its block's scope. If you didn't use curly brackets, even the declaration would cause compilation error. The resolution would look like
C#
string name = null; // or something else, but some initialization is absolutely required
if (Selection)
   name = "Hello";
else
   name = "something else";

You need to read on locality and scope topics before moving any further. Nearly any C# manual would include this topic.

Good luck,
—SA
 
Share this answer
 
v2
Comments
CPallini 10-Dec-13 1:33am    
5.
Sergey Alexandrovich Kryukov 10-Dec-13 1:45am    
Thank you, Carlo.
—SA
The other solutions provided a way to fix your code. You might be also interested in the reason that happens. Have a look, for instance to "The Scope and Lifetime of Variables in C sharp"[^].
 
Share this answer
 
Comments
Maciej Los 9-Dec-13 16:00pm    
Good point!
+5, Carlo!
CPallini 9-Dec-13 16:19pm    
Thank you.
Sergey Alexandrovich Kryukov 9-Dec-13 18:27pm    
Short informative one, a 5.
(I tried to give OP a chance to find the topic in some manual independently, but you nearly failed me. :-)
—SA
CPallini 10-Dec-13 1:33am    
Thank you, Sergey.
Joezer BH 10-Dec-13 1:59am    
5ed!

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