Question

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?

Was it helpful?

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.

OTHER TIPS

using statement rovides a convenient syntax that ensures the correct use of IDisposable objects.

The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object.

The CultureChanger instance will stay "alive" throughout the using block and its Dispose method will be called on the closing curly brace '}' of the using statemnet. So the answer to you question is: There is no risk that the CultureChanger could get cleaned up.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top