4

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

3
  • what is your if condition ? Commented Mar 1, 2017 at 8:48
  • You can using(MyClass c1 = new MyClass(condition ? a : b)). Commented Mar 1, 2017 at 8:48
  • @AlessandroD'Andria a and b are different types, so the ternary operator won't compile against those directly. Commented Mar 1, 2017 at 8:51

4 Answers 4

6

You can use Conditional (Ternary) Operator.

int a;
string b;

using(MyClass c1 = (some condition) ? new MyClass(a) : new MyClass(b))
{
    SomeMethod();
}
Sign up to request clarification or add additional context in comments.

5 Comments

It's called a conditional ternary operator: msdn.microsoft.com/en-us/library/zakwfxx4(v=vs.100).aspx
+1 for being the only one to spot that a and b are different types so can't satisfy the ternary operator on their own.
@john - no, it's called the conditional operator. Some people choose to call it ternary because most languages only contain one ternary operator and it's the conditional operator.
@Damien_The_Unbeliever Oddly enough I call it the ternary operator but I have no prior experience with it from other languages lol, I must've just cottoned on to someone else calling it that for that very reason.
@Damien_The_Unbeliever I've updated my comment as per MSDN :) I was attempting to change it from "ternary if", but failed with my edit slightly.
2

How about:

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

Comments

2

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.

Comments

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

1 Comment

a and b are of different type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.