Can I Simplify this:
public override Valor Nome
{
get
{
return new Valor
{
ValorEntrada = "agência centro"
};
}
}
To something like this:
public override Valor Test => Valor.ValorEntrada = "Value";
Valor has a property called ValorEntrada and this receives a string.
>Solution :
Yes. But you still need the new operator with an object-initializer.
public override Valor Test => new Valor { ValorEntrada = "Value" };
However:
(I assume your Valor type is a class rather than a struct)
-
Returning
new Valorin a property-getter means potentially unnecessary managed-heap object allocations.- While allocations are "cheap" (I wouldn’t personally say that), the cost of GC isn’t.
- In .NET, property-getters should always be both side-effect-free and always safe to use regardless of the state of the containing object. While there’s nothing in the example code which seems to have side-effects, it does break caller’s expectations about object identity.
- For example, this is how the property will behave, and I’d argue this violates expectations:
Foo foo = new Foo(); Valor v1 = foo.Test; Valor v2 = foo.Test; Console.WriteLine( Object.ReferenceEquals( v1, v2 ) ); // "False"
-
The fact you’re using an object-initializer to set what looks like a required property instead of passing the
"Value"string via a constructor parameter suggests that yourValorclass is mutable.-
Which is bad, given the points above.
-
Because it means this will happen:
Foo foo = new Foo(); foo.Test.ValorEntrada = "x"; Console.WriteLine( foo.Test.ValorEntrada ); // "Value" not "x"
-