tags:

views:

398

answers:

3

I'm adding some code into a using block in a C# program. I'm sort of stuffing my app, which previously was a standalone into an existing body of code, so I need to do a bit of messing around to get it to fit properly. What it's ending up looking like is the following:

public class WrapperForMyOldApp
{

    public static ItemThatINeed item1;
    public static ItemThatINeed item2;

    public WrapperForMyOldApp () 
    {
        item1 = new ItemThatINeed();
        item2 = new ItemThatINeed();
    }

    public static go()
    {
        // some stuff that i need to do with items 1 and 2
    }
}

public class MainProgram 
{
    .
    .
    .

    public void MethodThatNeedsToMakeUseOfMyApp ()
    {
        ....
        using (WrapperForMyOldApp oldAPp = new WrapperForMyOldApp())
        {
            WrapperForMyOldApp.go();
        }
    }
}

Alright, so the question here is: Have I now crippled the effects of the using block and/or created any peculiar side effects that might adversely effect the class MainProgram? I believe that the Wrapper object and it's contents will be Disposed and execution will continue as expected but is there anything I need to be aware of that I'm overlooking?

thanks!

+5  A: 

Does your wrapper class implement IDisposable and you're just not showing it? If it's not disposable, then you don't need the using statement at all.

Jon B
+3  A: 

In order for this to work, you'll need to have WrapperForMyOldApp implement IDisposable.

The Dispose() call in WrapperForMyOldApp would then do your cleanup.

However, static objects are typically used for objects that have a lifetime beyond the single object. In general, for this type of usage, you'd make the ItemThatINeed instances non-static, generate them in your WrapperForMyOldApp constructor, then clean them up in WrapperForMyOldApp.Dispose().

With static objects, you're potentially creating a nightmare - you're constructing the object, and then saying you want to perform the cleanup (at the end of the using block), so you Dispose() method would be cleaning up the static objects. However, if they get used again, what should happen? What is the correct behavior if you create two WrapperForMyOldApp instances in 2 threads? I would consider these issues if you want deterministic cleanup.

Reed Copsey
very helpful - thank you.
sweeney
+1  A: 

Well, if WrapperForMyOldApp implements IDisposable, and your Dispose() implementation can be sure to get rid of any resources, then it should work... but there can be other side effects. The code could change global (static) state, such as culture etc. It could spawn threads. All sorts of things.

It isn't a bad approach, but you need to know what the code you are encapsulating does to know whether Dispose() is going to do anything useful.

Marc Gravell