Reputation: 555
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
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
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
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