Search code examples
c#usingobject-lifetime

Does a using block keep an object alive?


For some unit tests, I want to set the CurrentCulture to a particular culture (and then reverse these changes later). As I need to do this in several places, I was thinking of writing a CultureChanger class which saves the old culture and sets the new culture in its constructor, and then resets the old culture during its disposal.

Then I could use it like this:

using(new CultureChanger(culture)){  
    //some code and assertions with no references to the CultureChanger 
}

If I did this, is there a risk that the CultureChanger could get cleaned up sometime before the using block completes?


Solution

  • CultureChanger won't get cleaned up until after the using block "completes".

    The using block defines the scope for the object in much the same way a method does.

    There's no guarantee on when the object will be garbage collected after the block executes, but it won't happen before.