Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of unassigned local variable on finally block

When could i in this example be unassigned?

int i;
try
{
    i = 2;
}
catch
{
    i = 3;
}
finally
{
    string a = i.ToString();
}
like image 449
Diego Avatar asked Dec 11 '13 14:12

Diego


1 Answers

You could get a ThreadAbortException before i=2 runs, for example. Anyway, the C# compiler is not exceptionally smart, so it's easy to fool with contrived examples like the above one. It doesn't have to recognize every situation, and if it's not sure it is assigned, even if you are sure, it will complain.

EDIT: I was a bit quick on my first assumption. So to refine it, here's what I think. Code is guaranteed to run in order, or if an exception happens, it will jump to the handlers. So i=2 may not run if an exception happens before that. I still claim that a ThreadAbortException is one of the few reasons why this can happen, even you have no code which could produce exceptions. Generally, if you have any number of different exception handlers, the compiler cannot know in advance which one will run. So it doesn't try to make any assumptions about that. It could know that if 1) there is only 1 catch block and 2) it is typeless, then, and only then, that one catch block is guaranteed to run. Or, if there were multiple catch handlers, and you assigned your variable in every one of them, it could also work, but I guess the compiler doesn't care about that either. However simple it may seem, it is a special case, and the C# compiler team has a tendency to ignore those special cases.

like image 174
fejesjoco Avatar answered Oct 03 '22 14:10

fejesjoco