Hi guys. Can a variable be used outside the try block?

string responseString;
char response;
Console.WriteLine("1. If you would like to ... press A");
Console.WriteLine("2. If you would like to ... press B");
Console.WriteLine("3. If you would like to ... press C\n");
responseString = Console.ReadLine();                
try
{
   response = Convert.ToChar(responseString);
}                   
catch
{
   Console.WriteLine("Incorect input, please select only from A,B,C.");
}    
Console.WriteLine(response);//Use of unassigned local variable 'response'

I'd like to use response in some if else statements, like if response is A do this and so on, but I get Use of unassigned local variable 'response' error. Can it be used outside the try block?

Edited 6 Years Ago by forneamax: n/a

Yes you can, but you need to assign a value to it!

char response = char.Parse("X") ;

http://www.mycsharpwarehouse.com/

Hi guys. Can a variable be used outside the try block?

string responseString;
char response;
Console.WriteLine("1. If you would like to ... press A");
Console.WriteLine("2. If you would like to ... press B");
Console.WriteLine("3. If you would like to ... press C\n");
responseString = Console.ReadLine();                
try
{
   response = Convert.ToChar(responseString);
}                   
catch
{
   Console.WriteLine("Incorect input, please select only from A,B,C.");
}    
Console.WriteLine(response);//Use of unassigned local variable 'response'

I'd like to use response in some if else statements, like if response is A do this and so on, but I get Use of unassigned local variable 'response' error. Can it be used outside the try block?

Yes, it can used. But you must assign a value outside the try {} block. Assign a default value to response:

char response = '0';

Thanks

Now that looks very simple .
Thanks guys!

Edited 6 Years Ago by forneamax: n/a

This question has already been answered. Start a new discussion instead.