On the c # channel in the irc network
Rusnet I try to entertain people of the so-called. sketches. These are short puzzles, the solution of which requires some subtleties of the language and implementation, and which are not at all obvious to the person, with the subtleties mentioned are not familiar.
Etude number 1 channel already guessed, but his community so far, most likely, does not know.
If you were not present on the channel during the flipping of the etude - please in the comments. The solution will appear here after the problem is solved by a habrak (or if there is no solution for a long time).
So the question is:
in which case there is a need to write the following code (it is not worth discussing the relevance of the proposed design, it’s all a spherical horse in a vacuum):
bool b = x ? true : false;
')
By the way, one of the motives for writing this post was the use of invitations to Habr as incentives for solving a problem (while I got off with an invite to Google Wave). Therefore, I ask for help with karma.
PS Well, well done, they did it very quickly.
So the solution. The type of the object x should define the operators true and false and should not define the cast operator to type bool:
class X
{
public X(bool b)
{
inner = b;
}
private bool inner = false;
public static bool operator true(X x)
{
return x.inner;
}
public static bool operator false(X x)
{
return !x.inner;
}
}
...
X x = new X(false);
bool b = x ? true : false;
The first explicit solution was given by the
Baks user, and the CyberCore
habraiser indicated that there is a SqlBoolean class that almost corresponds to the specified one (although it has an explicit type conversion operator).
Thank you all!
PPS In order to completely clarify the picture, I will point out that the operators true and false can be used in if, while, etc., constructions, as well as in the ternary operator. However, explicitly assigning a boolean variable requires other operators.
PPPS Thanks for the karma, moved to .NET