Helio Santos
Helio Santos

Reputation: 6805

Is is possible to accomplish this with the ternary operator?

I was wondering if it's possible to refactor the following code using the ternary operator:

if (HasKey("pagesPause"))
{
  Pause(GetInt("pagesPause"));
}
else
{
  Pause();
}

for example:

Pause(HasKey("pagesPause") ? GetInt("pagesPause") : void);

It does not work with void thought (I'm using c#).

Is there any way to do it?

Upvotes: 0

Views: 73

Answers (3)

Neowizard
Neowizard

Reputation: 3017

I'd like to point out that Pause(Int) and Pause(void) Do no have the same signature (naturally), so it's impossible to do this the way you tried (one call to two functions of different signatures).
The problem gets even worse if you take into account the limitations on the ternary operator stated in other answers.

Upvotes: 2

Pete Kirkham
Pete Kirkham

Reputation: 49311

You could be a bit wasteful and use the conditional to select an action to call

(HasKey("pagesPause") ? () => Pause(GetInt("pagesPause")) : (Action)(Pause))();

Which fits the requirement though probably not the intent of simplifying the code.

Alternatively, if the no-arguments version is equivalent to calling with a given default parameter, you could find the value and pass that into Pause(int)

Pause (HasKey("pagesPause") ? GetInt("pagesPause") : INFINITY);

Though if there was a suitable default, I would be more likely to change GetInt so it checks for the key and takes a default value to use if there isn't one.

Pause ( GetIntOrDefault("pagesPause", INFINITY) );

Upvotes: 2

Sander
Sander

Reputation: 1314

I think that this is what you are looking for.

var pauseValue = HasKey("pagesPause") ? Pause(GetInt("pagesPause")) : Pause() ;

Upvotes: 0

Related Questions