What value is checked in a condition operation with value assignment to a variable?

1

I have a method that does a check and the return of this method I store in a variable of type bool .

When I execute this operation, does C # test the value of the variable or the return value of the method?

Example:

 bool retorno = default(bool);
 if ((retorno = conta.Saca(Convert.ToDouble(txtValor.Text))))
 {          
      // regra de négocio
 }
    
asked by anonymous 23.05.2017 / 19:36

2 answers

4

You have to look at the operator precedence and associativity table.

The parentheses used already give a guarantee of everything inside it will be executed before and the result of this whole expression is that it will be used by if . Therefore

Within this expression everything on the right side of = will run first since associativity is right to left. It would also take some time to execute the assignment since it has low precedence.

Taking the expression conta.Saca(Convert.ToDouble(txtValor.Text)) first will execute . since it has the highest precedence along with parentheses. It goes first because the associativity is from left to right, and it is more to the left. The same goes for what is inside each parenthesis. Then the execution will be:

temp = txtValor.Text
temp = Convert.ToDouble(temp)
temp = conta.Saca(temp)
retorno = conta.Saca(temp)
if (retorno)

using System;
public class C {
    public int Main() {
        var conta = new Conta();
        var txtValor = new Form();
        bool retorno;
        if ((retorno = conta.Saca(Convert.ToDouble(txtValor.Text)))) {
            Console.WriteLine(retorno);
            return 1;
        }
        return 0;
     }
}

public class Conta {
    public bool Saca(double x) => true;
}

public class Form {
    public String Text;
}

See running on .NET Fiddle . Also put it on GitHub for future reference .

In fact IL shows this:

IL_000b: ldloc.0              //bool retorno;
IL_000c: ldfld string Form::Text //txtValor.Text
IL_0011: call float64 [mscorlib]System.Convert::ToDouble(string) //Convert.ToDouble(txtValor.Text)
IL_0016: callvirt instance bool Conta::Saca(float64) //conta.Saca(Convert.ToDouble(txtValor.Text))))
IL_001b: dup                  // Duplicate the value on the top of the stack
IL_001c: stloc.1              //retorno = conta.Saca(Convert.ToDouble(txtValor.Text)))
IL_001d: brfalse.s IL_0027    //if ((retorno = conta.Saca(Convert.ToDouble(txtValor.Text)))) {

See in SharpLab .

Precedence table:

    
23.05.2017 / 19:54
3

The code will test the value of the return variable, which in the case received the return value of the method

bool retorno = default(bool);
if ((retorno = conta.Saca(Convert.ToDouble(txtValor.Text))))

is equivalent to

bool retorno = default(bool);
retorno = conta.Saca(Convert.ToDouble(txtValor.Text));
if (retorno)
    
23.05.2017 / 19:40