What's the false operator in C# good for?

Posted by Jakub Šturc on Stack Overflow See other posts from Stack Overflow or by Jakub Šturc
Published on 2008-08-28T20:06:01Z Indexed on 2010/03/16 8:46 UTC
Read the original article Hit count: 338

Filed under:
|
|

There are two weird operators in C#:

If I understand this right these operators can be used in types which I want to use instead of a boolean expression and where I don't want to provide an implicit conversion to bool.

Let's say I have a following class:

    public class MyType
    {
        public readonly int Value;

        public MyType(int value)
        {
            Value = value;
        }

        public static bool operator true (MyType mt)
        {
            return  mt.Value > 0;
        }

        public static bool operator false (MyType mt)
        {
            return  mt.Value < 0;
        }

    }

So I can write the following code:

    MyType mTrue = new MyType(100);
    MyType mFalse = new MyType(-100);
    MyType mDontKnow = new MyType(0);

    if (mTrue)
    {
         // Do something.
    }

    while (mFalse)
    {
        // Do something else.
    }

    do
    {
        // Another code comes here.
    } while (mDontKnow)

However for all the examples above only the true operator is executed. So what's the false operator in C# good for?

Note: More examples can be found here, here and here.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET