O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required