Click here to Skip to main content
15,885,537 members

Response to: Conditional using block

Revision 2
You are missing something.

Your code sample may mean the different things. Look at the constructor class2.class2. It may mean:

Single constructor based on polymorphism of the type class1:
C#
class class1 : IDisposable {/* ... */}

class class2 : IDisposable {
   internal class2(class1 variable) {/* ... */}
   //...
}

// which is based on this inheritance:
class class2 : class1, IDisposable {/* ... */}


The same code fragments could be implemented in different content, where the classes class1 and class2 are unrelated:
C#
class class2 {
   internal class2(class1 variable) {/* ... */}
   internal class2(class2 variable) {/* ... */}
   //...
}


Are you starting to get it? If you use polymorphism, you can optimize your code and avoid "if":
C#
static void AMethod(bool useClass2) {
    using (Class1 variable1 = new Class1()) {
        Class1 factoryParameter = null;
        if (useClass2)
            factoryParameter = variable1;
        using (Class1 variable2 = Class1Factory(factoryParameter)) {
            using (Class3 variable3 = new Class3(variable2)) {
                variable3.DoSomething();
            } //variable3 is disposed here
        } //variable2 is disposed here
    } //variable1 is disposed here
} //AMethod

static Class1 Class1Factory(Class1 factoryParameter) { // important: polymorphic return
    if (factoryParameter == null)
        return new Class1();
    else
        return new Class2(factoryParameter);
} //Class1Factory


What to do in the more general case, when those IDisposable classes/structures are unrelated? You can leave your "naive" separate implementation putting both samples together with one "if" operator, but it could look too much messed up if you have greater level of nesting (which easily can be the case).

There is another way of doing thing. First, the using statement is equivalent to some try-finally block (or nested blocks). You can literally use it; it can be more compact then using, because try-finally is more general. But you can also use the special and well known technique:

Create a special "Disposal" class which can put all instances to be disposed in some container. Create only the instance of such class under using with only one level of nesting. Do you need to explain you more? I thing you should get an idea. If not just yes, your follow-up questions are very welcome — it's always a pleasure to deal with correctly formulated and sensible questions.

[EDIT]

I think most important criterion here would be to avoid any repeated code. I think you understand it. Please see:
http://en.wikipedia.org/wiki/Don%27t_repeat_yourself[^].

My very best wishes,
—SA
—SA
Posted 12-Sep-12 14:17pm by Sergey Alexandrovich Kryukov.
Tags: ,