What is the benefit to use one way than the other one between read-only fields and getter-only properties?

Viewed 67

Although there are already the similar questions, I haven't known if a use within them has more gains for performance so I have a question of it.

I heard read-only fields can be replaced at all constructors of their classes. But over the actual compilation environments including VS 2019, every properties have been able to be done regardless of whether they've had both methods or getters only. Their setters haven't been significant to get compiled successfully.

Here is the code below about this problem:

public class MyClass {
    public readonly int value_field;
    public int value_property { get; }
    
    public MyClass(int x) {
        this.value_field = x; // It's understandable
        this.value_property = x; // This doesn't cause any errors.
    }
}

Then, what is a better choice for performance and productivity?

1 Answers

Firstly, I don't think there will be any difference regarding their performance, take a look at the following code, that's how the compiler treats your code and it seems the property's BackingField declaration has been marked as read-only just like what you've declared for your field (because you've declared your property as a getter-only property):

public class MyClass
{
    public readonly int value_field;

    [CompilerGenerated]
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private readonly int <value_property>k__BackingField;

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

    public MyClass(int x)
    {
        value_field = x;
        <value_property>k__BackingField = x;
    }
} 

And secondly, if you want to declare a real getter-only property which cannot be initialized from the constructor, you need to do something like this:

public int value_property { get { return 1; } }

And finally, the reason to why you can initialize your read-only values from the constructor is that, it is a new feature in C#6 that allows you to create read-only properties and initialize their values from the constructor. This is the reference.

Related