Is it possible to do assignment with shorter object initializer?

1

Is there any way for the third instance to work with subtraction?

    private void btnGrasieli_Click(object sender, EventArgs e)
    {

        /*Isto funciona
        Bbanco = new Banco();
        Bbanco.Valor = Bbanco.Valor - 50;*/

        /*Isto funciona
        Bbanco = new Banco();
        Bbanco.Valor -= 50;*/

        **/*Isto não funciona*/**
        Bbanco = new Banco() { Valor -= 50 }; 
        MessageBox.Show(Bbanco.Valor.ToString());
    }
    
asked by anonymous 14.08.2017 / 04:59

1 answer

0

You have not finished declaring the variable before ; , since literal operators / values are not valid.

You can make a "Gambiarra" that organizes the code if you are using C # 3.0 +:

public static void Main()
{
    Banco Bbanco = new Banco; { Bbanco.Valor -= 50; }
    Console.WriteLine(Bbanco.Valor);
}

This does not make much sense since you are creating a Banco whose literal value for Valor already exists. I believe it is 0 in principle, but if you are creating another variable, why not put your value directly in it? If you want to create a bank with debt of $ 40.00 do the following:

Banco Bbanco = new Banco {Valor = -40};

Now if you create a bank from another bank, you can subtract by the same value in several ways:

Banco Bbanco = new Banco() {Valor = 125};
Banco Cbanco = new Banco() {Valor = Bbanco.Valor - 50};

Console.WriteLine("Bbanco = {0} Cbanco = {1}", Bbanco.Valor, Cbanco.Valor);

// Saídas:
// Bbanco = 125 Cbanco = 75

See working at .NET Fiddle .

    
14.08.2017 / 20:36