Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat's the false operator in C# good for?
    text
    copied!<p>There are two weird operators in C#:</p> <ul> <li>the <a href="http://msdn.microsoft.com/en-us/library/6x6y6z4d.aspx" rel="noreferrer">true operator</a></li> <li>the <a href="http://msdn.microsoft.com/en-us/library/6292hy1k.aspx" rel="noreferrer">false operator</a></li> </ul> <p>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.</p> <p>Let's say I have a following class:</p> <pre><code> public class MyType { public readonly int Value; public MyType(int value) { Value = value; } public static bool operator true (MyType mt) { return mt.Value &gt; 0; } public static bool operator false (MyType mt) { return mt.Value &lt; 0; } } </code></pre> <p>So I can write the following code:</p> <pre><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) </code></pre> <p>However for all the examples above only the true operator is executed. So what's the false operator in C# good for?</p> <p><em>Note: More examples can be found <a href="http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/truefalseoperatorforComplex.htm" rel="noreferrer">here</a>, <a href="http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/OverloadtrueandfalseforTwoDimension.htm" rel="noreferrer">here</a> and <a href="http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/trueandfalseoperator.htm" rel="noreferrer">here</a>.</em></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload