LastTribunal
LastTribunal

Reputation: 1

Trigger function(s) based upon Boolean result without using the iF word

if(someBoolTest()) dothis()
else dothat();

or just

if(someBoolTest()) dothis();

Wouldn't it be nice to do something like:

someBoolTest() => {dothis(),dothat()}

or

someBoolTest() => dothis()

Is this done in other languages? How do we do this in C#? (I don't think we can, so then why not?)

EDIT: I am aware of ternary ops, but that doesn't make it look any better. Would be nice to do this with some form of lambda with delegates..

Upvotes: 1

Views: 492

Answers (4)

Alex
Alex

Reputation: 13224

You can, but should not, do something that resembles the syntax that you mentioned, by doing something stupid like writing an extension method over a bool type, as shown in the below example:

public static class UselessExtensions
{
    public static void WhenTrue(this bool evaluatedPredicate, Action whenTrue)
    {
        if (evaluatedPredicate)
            whenTrue();
    }
}

public static class TryingUselessExtensions
{
    public static bool SomeBoolTest()
    {
        return true;
    }

    public static void DoIt()
    {
        SomeBoolTest().WhenTrue(() => Console.WriteLine(true));
    }
}

Upvotes: 2

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

How do we do this in C#?

Using the if-else clause, just as you did in your example.

You could be creative and create something of this sort:

(SomeBoolTest() ? (Action)DoThis : DoThat)();

But that is terribly unreadable code, don't do that.

Upvotes: 4

I believe ternary operators are what you're looking for:

variable = condition ? value_if_true : value_if_false

So, for example you want an int to equal 0 if your condition is met, and 3 if it is not:

int this = 500;
int that = 700;
int n = (this==that) ? 0 : 3;

In this case n would be assigned the value of 3! There's a good wikipedia page on this, head on over and give it a look :)

Wikipedia page on ternary operators

Upvotes: 0

Winky2222
Winky2222

Reputation: 46

You do it like this

    bool myBool = true;
    bool newBool;
    public void Main()
    {
        MyFunction( newBool = (aFunctionThatReturnsABool == true) ? true: false);
    }

    public void MyFunction (bool aBool)
    {
        // stuff based on the bool
    }

But what are you actually trying to do?

Upvotes: -1

Related Questions