Search code examples
c#public-fields

What is the purpose of the => operator on public fields?


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;
        }
    }
}

Solution

  • 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.