user1046403
user1046403

Reputation: 555

Changing bool values to opposite of the initial value

This maybe sound strange to you but I'm too lazy to write everytime like

if (threadAlive)
{
            threadAlive = false;
}
        else
{
            threadAlive = true;
}

isn't there is something like int++ or int-- to change bool value to opposite of its value?

Upvotes: 36

Views: 97198

Answers (7)

Avram Tudor
Avram Tudor

Reputation: 1526

You can't overload operators for basic types if that's what you're looking for.

As everyone else mentioned already, this is by far your best option:

threadAlive = !threadAlive;

You can however, although is something I would never recommend, create your own bool type and overload the ++ or whatever operator you wish to invert your value.

The following code is something that should never be used anyway:

public class MyBool
{
    bool Value;

    public MyBool(bool value)
    {
        this.Value = value;
    }

    public static MyBool operator ++(MyBool myBoolean)
    {
        myBoolean.Value = !myBoolean.Value;
        return myBoolean;
    }
}

You can also create your own extension method but that won't be be a better way either.

Upvotes: 7

xanatos
xanatos

Reputation: 111830

Yes, there is!

threadAlive ^= true;

(this is a C# joke, in the most general case it won't work in C/C++/Javascript (it could work in C/C++/Javascript depending on some conditions), but it's true! ^ is the xor operator)

Upvotes: 24

Kyle_the_hacker
Kyle_the_hacker

Reputation: 1434

The logical negation operator ! is a unary operator that negates its operand. It is defined for bool and returns true if and only if its operand is false and false if and only if its operand is true:

threadAlive = !threadAlive;

Upvotes: 11

ouah
ouah

Reputation: 145829

Use the ! operator:

bool b = true;

b = !b;   // b is now false

Upvotes: 7

Habib
Habib

Reputation: 223207

This would do it:

threadAlive = !threadAlive;

The correct term is Toggle

Upvotes: 17

piokuc
piokuc

Reputation: 26164

Very simple:

threadAlive = ! threadAlive;

Upvotes: 5

p.s.w.g
p.s.w.g

Reputation: 148990

Just do this:

threadAlive = !threadAlive;

Upvotes: 84

Related Questions