Normally the compiler forbids any use of unassigned local variables, but not in the following case. Why?
private void Main()
{
// This local variable is unassigned.
string myVar;
try
{
// The Throw() method prevents the assignment from happening...
myVar = Throw();
}
finally
{
// ... so myVar is still unassigned.
}
// Here we use myVar, which is unassigned, and the compiler is not complaining.
if (myVar.Equals("Something"))
{
// ...
}
}
private string Throw()
{
throw new Exception();
}
The exception in the example is not caught by Main(). Therefore, if the exception is thrown, the code after the finally block is unreachable, and if the exception is not thrown, the assignment occurs. That's why in any case a use of an unassigned variable cannot happen. And since it cannot happen, the compiler doesn't report it.