Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If (instance) / implicit boolean conversion on a custom class

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) { }
  1. And how do I assign it to a value without use .Value =?

Thanks for you help :)

like image 819
SHEePYTaGGeRNeP Avatar asked Feb 14 '18 13:02

SHEePYTaGGeRNeP


2 Answers

You can define an implicit conversion to bool :

public static implicit operator bool(InterlockedBool obj)
{
    return obj.Value;
}
like image 91
Titian Cernicova-Dragomir Avatar answered Oct 30 '22 09:10

Titian Cernicova-Dragomir


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

like image 11
Martin Verjans Avatar answered Oct 30 '22 09:10

Martin Verjans