-1

What is the purpose of using the => operator with public fields in a C# class? I saw this being done in the unit test code in the eShopOnWeb ASP.NET Core project hosted on GitHub. Is it actually a property with the => operator referring to the value returned from the getter method? The code in question is shown below:

using Microsoft.eShopWeb.ApplicationCore.Entities.OrderAggregate;

namespace Microsoft.eShopWeb.UnitTests.Builders
{
    public class AddressBuilder
    {
        private Address _address;
        public string TestStreet => "123 Main St.";
        public string TestCity => "Kent";
        public string TestState => "OH";
        public string TestCountry => "USA";
        public string TestZipCode => "44240";

        public AddressBuilder()
        {
            _address = WithDefaultValues();
        }
        public Address Build()
        {
            return _address;
        }
        public Address WithDefaultValues()
        {
            _address = new Address(TestStreet, TestCity, TestState, TestCountry, TestZipCode);
            return _address;
        }
    }
}
Raj Narayanan
  • 2,443
  • 4
  • 24
  • 43
  • 3
    They are not public fields, they are `get` only properties. – Enigmativity Jun 12 '21 at 01:55
  • 1
    Does this answer your question? [Why use expression-bodied properties for primitive values?](https://stackoverflow.com/questions/62958381/why-use-expression-bodied-properties-for-primitive-values) and [What is the benefit of using “Expression Bodied Functions and Properties”](https://stackoverflow.com/questions/40321431/what-is-the-benefit-of-using-expression-bodied-functions-and-properties) –  Jun 12 '21 at 01:56
  • [Expression-bodied members (C# programming guide)](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members) | [Lambda expressions (C# reference)](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-expressions) –  Jun 12 '21 at 01:57

1 Answers1

1

Take this class:

public class Foo
{
    public int Bar { get; } = 42;
    public int Qaz => 42;
}

That outputs the following when decompiled:

public class Foo
{
    [CompilerGenerated]
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private readonly int <Bar>k__BackingField = 42;

    public int Bar
    {
        [CompilerGenerated]
        get
        {
            return <Bar>k__BackingField;
        }
    }

    public int Qaz
    {
        get
        {
            return 42;
        }
    }
}

You're looking at a shorthand for get only properties.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172