Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set a getter using => C#

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 Valor in 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 your Valor class 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"
      
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading