Roi Shabtai
Roi Shabtai

Reputation: 3085

Method dispose functionality C#

Is there a way to dispose method variables without using try-finally block in C# 2010 (.Net 4)?

The story: I have few files handler methods. Each handler (method) can abort in the middle of execution. I like to dispose all method's object before exiting the method. The option to compose dispose method for each handler is not an option.

Thank you

This demonstrate the general idea: `public static class Comparison { private static bool CompareXmls(...) { //has 7 object to be disposed in 3 exit points acordding to 4 conditions

        //General method flow:

        //1. init part of the object

        //2. if(!<condition1>)
                //disposed objects
                //exit method

        //3. perform some actions

        //4. init some of the other objects

        //2. if(!<condition2>)
                //disposed objects
                //exit method

        //and so on...
    }

    private static bool CompareJpgs(...)
    {
        //has 12 object to be disposed in 10 exit points acordding to 4 conditions
    }

    private static bool CompareBitMaps(...)
    {
        //has 5 object to be disposed in 3 exit points acordding to 4 conditions
    }

    private static bool CompareTxts(...)
    {
        //has 12 object to be disposed in 10 exit points acordding to 4 conditions
    }
}`

I have another 7 comparison methods

Upvotes: 0

Views: 241

Answers (2)

Michael Sagalovich
Michael Sagalovich

Reputation: 2549

using? Refer here for the full description on how and why to use http://msdn.microsoft.com/en-us/library/yh598w02(v=VS.100).aspx. A sample would be

using (MyDisposableType disposable1 = GetDisposable1(), disposable2 = GetDisposable2() /*,...*/)
{
    //your actions
}

after exiting from the using block, all disposable objects declared in its header will be disposed.

If your disposable objects are of different types, you can use nested usings:

using (MyDisposableType1 disposable1 = GetDisposable1())
{
    using (MyDisposableType2 disposable2 = GetDisposable2())
    {
        //more usings if needed, and then your actions
    }
}

Upvotes: 1

Tom Squires
Tom Squires

Reputation: 9286

I would put the method on an object that impiments idisposible and call this.dispose() in a finally block

Upvotes: 0

Related Questions