I have code that basically looks like this (it isn’t actually object, but rather a custom class):
object thing
try {
thing = new object();
......
} catch { stuff }
finally {
if (thing != null) { some clean up code }
But VS is not letting me do this because it says I am referencing an unassigned variable. I am well aware it could be unassigned when this code is run, which is why the null check is there. I don’t want to instantiate the object outside of the try block because it does a fair bit and could throw an exception, and I would prefer against wrapping the whole thing in another try/catch block just so I can instantiate it up there. Is there something else I can do?
“Unassigned” isn’t the same as “null”. Your code is simply invalid – you need to fix it.
It’s very easy here – just initialize the variable to
nullto start with:Now it will definitely have a value (a null reference) so you’re allowed to read from it in the
finallyblock.The point is that local variables cannot be read before the point at which the compiler can prove that a value (whether null or not) has definitely been assigned. Effectively, local variables don’t have “default values”.
(Mind you, I’d normally use
IDisposablefor clean-up code, along with ausingstatement.)