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?

Recommended Answers

All 3 Replies

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!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.