How to avoid 'Unassigned Local Variable' defined inside a try-catch block
WebRequest myRequest = WebRequest.Create(baseUri.OriginalString);
WebResponse myResponse = null;
Stream myStream= null;
StreamReader reader =null;
This will assign the variables
Edit:
If you do it like this you should add an if outside your try/catch
if(reader != null)
{
Regex regex = new Regex(@"\s*(?i)href\s*=\s*(\""([^""]*\"")|'[^']*'|([^'"">\s]+))", RegexOptions.IgnoreCase);
MatchCollection splits = regex.Matches(reader.ReadToEnd());
}
Do note in your case its better to put everything in the try/catch block
You are using a variable, that is assigned in a try/catch block, outside that block. You'll want to move the whole code into the try block.
You could assign null
to it like @Svexo proposed, but this will throw an exception should the stream error out.
The compiler says use of unassigned variable
because the code after the try/catch block will be executed anyway.
If you have an exception, you catch it, then you run the code after it. That's why you get this error.
You can either
- assign
null
to the local variables and then test if they're null before executing the rest of the code - return the function in your catch block.
- or move all the code into the try block as suggested @Femaref