Hi,
I'd like to hear your opinions on conditional
using
blocks. The thing is that I need to have a structure like the following:
public void AMethod(bool useClass2) {
using (Class1 variable1 = new Class1()) {
using (Class2 variable2 = new Class2(variable1) {
using (Class3 variable3 = new Class3(variable2) {
variable3.DoSomething();
}
}
}
}
Now the problem is that based on the parameters of the method the middle using block should either be included or excluded. If the parameter
useClass2
is
true
, the code should be executed as above but if the parameter is
false
, then the execution should look like the following:
public void AMethod(bool useClass2) {
using (Class1 variable1 = new Class1()) {
using (Class3 variable3 = new Class3(variable1) {
variable3.DoSomething();
}
}
}
So based on the parameter, the middle using block may be included and the innermost using block uses either Class1 or Class2.
Now, this could be done with for example:
- Separate, specialized methods (no need for parameter)
- using If..Else structure for the Class2, and duplicating the inner code on necessary parts etc.
But I'm curious, am I missing something obvious? Would there be an easy, clean way to conditionally use or bypass the instance of the Class2?
The classes (1-3) are .Net framework classes derived from File.IO.Stream, for example
FileStream
,
CryptoStream
etc.