I have the following class:
public class InterlockedBool
{
private int _value;
public bool Value
{
get { return _value > 0; }
set { System.Threading.Interlocked.Exchange(ref _value, value ? 1 : 0); }
}
public static bool operator ==(InterlockedBool obj1, bool obj2)
{
return obj1.Value.Equals(obj2);
}
public static bool operator !=(InterlockedBool obj1, bool obj2)
{
return !obj1.Value.Equals(obj2);
}
public override bool Equals(bool obj)
{
return this.Value.Equals(obj);
}
}
My question is: Can I check if Value is true, without == true
? The operator override works, but can I also use it like so?
InterlockedBool ib = new InterlockedBool();
if (ib) { }
Instead of (this works, but normally I omit the == true
in if
statements.
if (ib == true) { }
.Value =
?Thanks for you help :)
You can define an implicit conversion to bool :
public static implicit operator bool(InterlockedBool obj)
{
return obj.Value;
}
You need to be able to convert your object to and from a boolean
Implicit Conversion
Your object to a boolean:
public static implicit operator bool(InterlockedBool obj)
{
return obj.Value;
}
Then a boolean to your object:
public static implicit operator InterlockedBool(bool obj)
{
return new InterlockedBool(obj);
}
Then you can test it:
InterlockedBool test1 = true;
if (test1)
{
//Do stuff
}
Explicit Conversion
If you want the users of this class to be aware that there is a conversion happening, you can force an explicit cast :
public static explicit operator bool(InterlockedBool obj)
{
return obj.Value;
}
public static explicit operator InterlockedBool(bool obj)
{
return new InterlockedBool(obj);
}
Then you must explicitly cast your objects:
InterlockedBool test1 = (InterlockedBool)true;
if ((bool)test1)
{
//Do stuff
}
EDIT (due to OP comment)
In the conversion from boolean to your object, I call a constructor that you did not mention, here is how I would build it:
public InterlockedBool(bool Value)
{
this.Value = Value;
}
Therefore the setting of the value is guranteed thread-safe
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With