简体   繁体   中英

C# initialize variable after checking a condition

I need to use a variable initialized only after checking a condition.
I get the error:

Use of unassigned local variable

Does not the compile check if the conditions are the same?
This is my code. How can I solve it?

Web web;
if (myCondition){
    //heavy operation
    web = site.openWeb();
}

for ( n loop)
{
    //do stuff
    if (myCondition){
        //use web
    }
}

if (myCondition){
    web.Dispose()
}

Simply set it to null to make sure it is initialized at all:

Web web = null;

And then, when disposing, better check that variable is not null, to make sure you dispose always when necessary:

if (web != null){
    web.Dispose();
}

Also note that you won't all Dispose if an exception is thrown in the loop. So you might want to wrap it all in try/finally.

But as it already came that far - have you considered using ?

Try something like this:

Web web =  null;
if (myCondition)
{
    //heavy operation
    web = site.openWeb();
}

for ( n loop)
{
    //do stuff
    if (myCondition)
    {
        //use web
    }
}

if (myCondition)
{
    web.Dispose()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM