Following this very interesting issue which was originated from this question -
I want to take 1 steps back please (removed the dynamic environment) :
Looking at this code : ( a variant of this one)
void Main()
{
int a;
int b = 100;
Console.WriteLine(X.M(1, out a));
}
public class X
{
public int H=0;
public static X M(int x, out int y)
{
Console.WriteLine("x = "+x);
y = x;
return new X(x);
}
public X(){}
public X(int h)
{
H=h;
}
public static bool operator false(X x) {Console.WriteLine("in false operator for "+ x.H); return true; }
public static bool operator true(X x) {Console.WriteLine("in true operator for "+ x.H); return true; }
public static X operator &(X a, X b) {Console.WriteLine("in & operator for "+ a.H+","+b.H); return new X(); }
public static implicit operator bool (X x) {Console.WriteLine("in bool operator for "+ x.H);return true; }
}
The result is :
x = 1
in bool operator for 1
True
This is understood :
- The
x = 1
is from the method itself ( usingConsole.Writeline
) in bool operator for 1
is from the implicit operator fromX
toBool
(so -Console.WriteLine
treats the whole expression asConsole.Writeline(bool)
)- The last "True" is from the "return true" in the
operator bool (X x)
OK - So let's change
Console.WriteLine(X.M(1, out a));
to
Console.WriteLine(X.M(1, out a) && X.M(2, out b));
Now - the result is :
x = 1
in false operator for 1
in bool operator for 1
True
2 questions :
Why does this
in false operator for 1
executes ? I don't see any reason forfalse
to be present here.I could understand why the right part in
X.M(1, out a) && X.M(2, out b)
won't executes ONLY if the left part isfalse
- but again I don't see how the left part can be false. It does returntrue
(according to my first code)
NB
I've read many times the answers from the post :
Jon said :
The second && is a normal && between two bool expressions - because Nop returns bool, and there's no &(X, bool) operator... but there is a conversion from X to bool.
So it's more like:
bool first = X.M(1, out a) && X.M(2, out b);
if (first && Nop(a, b))Now first is true even though only the first operand of && has been evaluated... so b really hasn't been assigned.
Still I don't understand : "first is true
(????) even though only the first operand of && has been evaluated"