3.8. Indirectly Overloading the &&, ||, and ?: Operators

Problem

You need to control the handling of the &&, ||, and ?: operators within your data type; unfortunately, these operators cannot be directly overloaded.

Solution

Overload these operators indirectly by overloading the &, |, true, and false operators:

public class ObjState
{
    public ObjState(int state)
    {
        this.state = state;
    }

    public int state = 0;

    public static ObjState operator &(ObjState obj1, ObjState obj2)
    {
        if (obj1.state >= 0 && obj2.state >= 0)
            return (new ObjState(1));
        else
            return (new ObjState(-1));
    }

    public static ObjState operator |(ObjState obj1, ObjState obj2)
    {
        if (obj1.state < 0 && obj2.state < 0)
            return (new ObjState(-1));
        else
            return (new ObjState(1));
    }

    public static bool operator true(ObjState obj)
    {
        if (obj.state >= 0)
            return (true);
        else
            return (false);
    }

    public static bool operator false(ObjState obj) 
    {
        if (obj.state >= 0)
            return (true);
        else
            return (false);
    }

    public override string ToString( )
    {
        return (state.ToString( ));
    }
}

This technique gives you complete control over the operations of the &&, ||, and ?: operators.

Alternatively, you can simply add an implicit conversion to bool:

public class ObjState
{
    public ObjState(int state)
    {
        this.state = state;
    }

    public int state = 0;

    public static implicit operator bool(ObjState obj) 
    {
        if (obj.state == 0)
        {
            throw new InvalidOperationException( );
        }

        return (obj.state > 0);
    }
}

This technique implements strict Boolean logic; the first technique (overriding ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.