Dodeius
Dodeius

Reputation: 125

Is there something like the conditional operator but for expressions?

For assignments of a value to a varbiable, I can use the following:

className = special ? "Test" : "";

But what if I instead want to call a function only if special is true? I have tried

special?classNameIsTest() : classNameIsNotTest();

But that does not work. Is there something like this? Or should I just keep using

if(special) classNameIsTest();
else classNameIsNotTest();

Upvotes: 1

Views: 70

Answers (3)

Dan Bryant
Dan Bryant

Reputation: 27505

Let me preface this answer by saying I don't actually recommend doing this, but you can play some interesting syntactical tricks with extension methods.

public static void Then(this bool x, Action whenTrue, Action whenFalse)
{
   if (x) whenTrue();
   else whenFalse();
}

You then use it like special.Then(Test1, Test2);

Upvotes: 2

Christian Müller
Christian Müller

Reputation: 1022

You can use this phrase

var dummy = special ? Test1() : Test2();

But both can't be void and must have the same return type.

So... I usually wouldn't use this and stick with "if". You should only use this expression to make the code more maintainable and readable.

In your case... I would assume it will make the code less understandable.

Upvotes: 3

M.kazem Akhgary
M.kazem Akhgary

Reputation: 19149

If both methods have same signature (same parameters and same return type) you can do this. for example if both methods are void and take no parameters

(special ? (Action)Foo : Bar).Invoke();

If both methods take an integer but are void

(special ? (Action<int>)Foo : Bar).Invoke(20);

If both methods take an integer, an string, and return boolean

bool result = (special ? (Func<int, string, bool>)Foo : Bar).Invoke(20, "...");

So you can kind of do this but i don't do that because this is not usual way of programming. it just adds boilerplate code.

Upvotes: 4

Related Questions