Any better way to use the if else statement when using the "using" statement of a block?

I have a scenario in which I have two new objects in which only one needs to be initialized according to the condition.

But I use the "using" block statement to initialize a new object.

How can i achieve this? Please refer to the scenario below.

int a;
string b;

if()//some codition
{
    using(MyClass c1 = new MyClass(a))
    { 
            SomeMethod();
    }
}
else
{
    using(MyClass c1 = new MyClass(b)
    {
             SomeMethod();
    }
}

Is there a better way to achieve this in one condition or in some other way to reduce the code? because I call the same method in both conditions.

Thanks in advance.

Regards, Anish

+4
source share
4 answers

() .

int a;
string b;

using(MyClass c1 = (some condition) ? new MyClass(a) : new MyClass(b))
{
    SomeMethod();
}
+6

:

using (var c1 = condition ? new MyClass(a) : new MyClass(b))
{
    SomeMethod();
}
+2

- ?

, .

using (MyClass c1 = condition ? new MyClass(a) : new MyClass(b))
{
    SomeMethod();
}

?: is the Ternary operator, which, as the name implies, works with 3 operands.

+2
source
  IDisposable target = somecondition ?  new MyClass(a)  : new MyClass(b) ;
  using (IDisposable c1 = target )
  {
                SomeMethod();
  }
+1
source

Source: https://habr.com/ru/post/1671113/


All Articles