florien
florien

Reputation: 506

Concise way of using conditional operator

I have this code, where LongMethodWithResult is a method that takes a long time to run:

object o = LongMethodWithResult() == someVal ? LongMethodWithResult() : someOtherResult;

Now the LongMethodWithResult method is evaluated two times, isn't it?

I know I could write a method that uses variables to store the result of the long method, something like this:

public static object ConciseConditionalOperator(object a, object b, object c)
{
    return a == b ? a : c;
}

But I would be interested in whether there is a best way of doing this, or some functionality served by C# or the .NET.

Any ideas are welcomed!

Upvotes: 0

Views: 120

Answers (2)

Peter B
Peter B

Reputation: 24137

In this specific case you could use this:

object o = LongMethodWithResult() == someVal ? someVal : someOtherResult;


If you prefer a different notation, or if you want to avoid specifying someVal twice, then you could create an Extension method (in a static class):

public static T IfEqualThenElse<T>(this T valueToCheck, T value1, T value2)
    where T : System.IEquatable<T>
{
    return valueToCheck.Equals(value1) ? value1 : value2;
}

Usage:

var o = LongMethodWithResult().IfEqualThenElse(someVal, someOtherResult);

Upvotes: 5

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

Generally you are right. In your example, the LongMethodWithResult is executed twice. To avoid that, you need to first store the result of LongMethodWithResult:

var result = LongMethodWithResult();
object o = result == someVal ? result : someOtherResult;

As Peter B said in your answer, the example you provided is a special case where you don't need that, as when LongMethodWithResult()'s result equals a value you already know, there's no need to call it again. You can just return the value you already know.

However, oftentimes the following is necessary:

var result = LongMethodWithResult();
object o = result == null ? defaultResult : result;

You can, however, replace the last construct with a simple:

object o = LongMethodWithResult() ?? defaultResult;

Upvotes: 1

Related Questions