0

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 by forneamax: n/a

3
Contributors
3
Replies
5
Views
7 Years
Discussion Span
Last Post by forneamax
Featured Replies
  • Yes you can, but you need to assign a value to it! [CODE] char response = char.Parse("X") ; [/CODE] [URL="http://www.mycsharpwarehouse.com/"]http://www.mycsharpwarehouse.com/[/URL] [QUOTE=forneamax;1089618]Hi guys. Can a variable be used outside the try block? [CODE]string responseString; char response; Console.WriteLine("1. If you would like to ... press A"); Console.WriteLine("2. If you would like to … Read More

  • Yes, it can used. But you must assign a value outside the try {} block. Assign a default value to [I]response[/I]: [CODE]char response = '0';[/CODE] Thanks Read More

1

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?

1

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

char response = '0';

Thanks

0

Now that looks very simple .
Thanks guys!

Edited by forneamax: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.