Is it possible to do assignment with shorter object initializer?

Asked

Viewed 47 times

1

Is there any way the third instance works with subtraction attribute?

    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());
    }
  • And if you use it like this: Banco Bbanco = new Banco { Valor -= 50 };

  • I tried too. : C

  • See here https://dotnetfiddle.net/LXxzhC

1 answer

0

You have not finished declaring the variable before the ;, because the assignment of operators/literal values will not be 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);
}

That doesn’t make much sense, because it’s creating a Banco which already has a literal value for Valor. I believe it is 0 of principle, but if you are creating another variable, why not put its value directly in it? If you want to create a bank with debt of R $ 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 on .NET Fiddle.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.