LukeBenVader1
LukeBenVader1

Reputation: 103

Difference between readonly field and private getter property

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

Is there a difference between using either one of these, or is it purely someone's preference?

Upvotes: 2

Views: 1091

Answers (1)

ekke
ekke

Reputation: 1410

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

Upvotes: 4

Related Questions