So var is unusable when you are using any kind of exception handling around initialisation? That seems like a massive drawback to its usefulness.
You're stuck between a rock and hard place, you need to define variables outside of the exception handled blocks (since the compiler cannot predict the route the execution will take within that context) but to a var you must initialise them to a type in order to use them.
How about this example, how would you refactor this into a var version of the same?
StreamReader sr = null;
string content;
try
{
sr = new StreamReader(@"C:\Temp\example.txt");
content = sr.ReadToEnd();
}
catch (Exception ex)
{
Console.WriteLine("Source: " + ex.Source + " Message: " + ex.Message);
return;
}
finally
{
if(sr != null)
sr.Close();
}
Console.Write(content);
Console.ReadKey();
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.