Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 208
Anish Avatar asked Dec 19 '22 09:12

Anish


1 Answers

You can use Conditional (Ternary) Operator.

int a;
string b;

using(MyClass c1 = (some condition) ? new MyClass(a) : new MyClass(b))
{
    SomeMethod();
}
like image 84
Vijay Avatar answered Dec 24 '22 03:12

Vijay