On Thu, 12 Jun 2008 11:41:20 -0700, <qg**********@mailinator.comwrote:
While we are talking about operator overload, could someone explain to
me how are you supposed to use the “true” and “false” unary operator
overload?
If I read the spec correctly, these operators are used when you have a
type that semantically can be thought of as "true" or "false" (that is, it
essentially has some boolean state). You pass in an instance of the type,
and the "true" operator returns the bool "true" if the type is in the
"true" state. The "false" would be the inverse (you're required to define
both, but I expect you'd generally just have one call the other and invert
the result. Any other design could start to get confusing.
You can take advantage of this to allow boolean operations on such a type,
even though you can't overload && and ||. By overloading & and |, as well
as "true" and "false", you allow the compiler to infer the correct && and
|| behavior. Paraphrasing the C# spec, where you have variables "x" and
"y" of a type T as described above, the expression "x && y" would be
evaluated as "T.false(x) ? x : T.&(x, y)" and the expression "x || y"
would be evaluated as "T.true(x) ? x : T.|(x, y)".
Since the type T would have the "true" and "false" operators overloaded,
the compiler can take the results from the & and | operators and convert
that from an instance of the type T to values of the actual "bool" type.
So the expressions above, which actually return a value of type T, could
then be run through the "true" or "false" operator, as appropriate to
whatever the final expression really is (I assume the compiler would use
the "true" operator for a plain expression and the "false" operator if
you've also used the negation operation !, but of course it could just
always use "true" and then perform whatever necessary logic on that
boolean after).
I don't know for sure why the language is like this. However, I can see
how designing it like this ensures that there is logical consistency
between the &&/|| operators and the &/| operators, any time the type
author decides they want their type to support both (it won't always make
sense for a type to support both, but in some cases it does).
It’s probably very obvious and I am sure goggling it will shed some
light about how this supposed to work but I figure I post this here
since is somewhat related with the OP question.
I don't think it's necessarily obvious at all, and for sure the MSDN docs
could do a much better job of elaboration. However, I definitely would
recommend that if these are questions you're curious about, you download
the C# spec, as it does generally answer these kinds of questions.
Of course, if you hadn't asked it, I never would have bothered to look at
the spec myself, and of course assuming my interpretation is useful, this
newsgroup would never have benefitted from having the question answer
posted here. So maybe it's better to just ask the question. :)
Pete