Anish
Anish

Reputation: 219

Any better way to use if else statement while using an “using” block statement?

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

But I am using the “using” block statement for initializing a new object.

How can I achieve it? Please refer the below scenario.

int a;
string b;

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

Is there any better way to achieve this in single condition or any other way to reduce the code? because I am calling the same method in both condition.

Thanks in advance.

Regards, Anish

Upvotes: 4

Views: 349

Answers (4)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48568

Is there any better way to achieve this in single condition or any other way to reduce the code?

Yes, you can.

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

?: is a Ternary operator which as the name suggests, works on 3 operands.

Upvotes: 2

Vijay
Vijay

Reputation: 543

You can use Conditional (Ternary) Operator.

int a;
string b;

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

Upvotes: 6

Caspar Kleijne
Caspar Kleijne

Reputation: 21864

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

Upvotes: 1

Matthew Watson
Matthew Watson

Reputation: 109597

How about:

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

Upvotes: 2

Related Questions