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
You can use Conditional (Ternary) Operator.
int a;
string b;
using(MyClass c1 = (some condition) ? new MyClass(a) : new MyClass(b))
{
SomeMethod();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With