1

Hello I'm very confused with the difference between a readonly field and a private getter property. I've seen people use both in their code but I simply don't understand what makes them different.

private readonly int num = 0;

// or //

private int Num
{
    get { return num; }
}

So is there a difference between using either one of these, or is it by someone's preference? I'm still beginner in C# & I have some experience with python, so apologies if this is a dumb question. :-)

LukeBenVader1
  • 93
  • 1
  • 1
  • 11
  • 2
    Cross-site dupe: https://softwareengineering.stackexchange.com/questions/372462/readonly-vs-private-getter-only-property-in-c-6 – Sweeper Jan 13 '21 at 02:35
  • 2
    Does this answer your question? [Are there any reasons to use private properties in C#?](https://stackoverflow.com/questions/3310186/are-there-any-reasons-to-use-private-properties-in-c) – Charlieface Jan 13 '21 at 03:11
  • Both helped me out tremendously, thank you – LukeBenVader1 Jan 13 '21 at 14:24

1 Answers1

3

Getters are usually used to encapsulate access to a field so that implementation logic is hidden from users, making the class more of a black box.

A private getter would only be accesibile to a person implmenting the class (or someone using reflection to access this field) so it wouldn't be useful for encapsulation so much as for implmenting logic in a more convenient way.

A readonly field can only be set in the constructor or field initialiser (which are in both performed in the constructor in the underlying IL), whereas the variable behind a private getter could be set at any time.

A readonly value type is immutable, which means the data held by it in memory will never change once the constructor has executed.

As an example of the difference:

private readonly immutableNum = 0; // this value will be always 0 (unless asigned something else in the constructor

private int num = 0; // this value can be changed anytime by internal logic in the class

private int Num
{
    get { Console.WriteLine("Accessed num"); return num; } // additional logic implemented in the getter that can't be done in a readonly field, 
    //num can be set/reset anytime, so its value can change
}

private immutableGetterNum => 6; //this value will never change

So, do you want to encapsulate access logic? Then you need to use a getter. Do you need to ensure that the value assigned to a field is not changed? Then use a readonly field (or a getter with no underlying field).

ekke
  • 1,280
  • 7
  • 13