Jonathan Woollett-light
Jonathan Woollett-light

Reputation: 3243

Issues with private variables and getters

It would seem I've come across a considerable lack in my understanding. I understand it is best practice to use a private variable within a class and access it via a public getter outside said class. Now when using C#s default getter method (private string Image { get; }) I cannot access the Image variable outside of this class (Console.WriteLine(items[i].Image);).

enter image description here

Although I could write a custom public getter, this seems absurd since having a private getter on a private variable that does nothing other than return the variable seems utterly redundant and thus makes me think I'm missing something.

Upvotes: 1

Views: 2350

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726529

When you declare

private string Image { get; }

you make a private read-only property, meaning that both the getter and the setter are private. In addition, the setter is inaccessible outside constructors / initializers.

Changing it to

public string Image { get; }

would give you a public read-only property. This roughly corresponds to the following arrangement:

  • The getter is public, i.e. accessible to everyone inside and outside the class
  • The setter is private*, i.e. accessible only inside the class.
  • The property is read-only, so the additional restriction on the private setter is that it must be accessed through a constructor or an initializer.

In Java I would create a private variable and a public getter. Is this effectively the version of that in C#?

An equivalent of this in Java would be a private final field, because C# restricts access to setter outside the constructor.

* Actually, there is no setter for read-only properties. Assignments write directly to backing storage for the property, without going through a setter. The distinction between having a private setter accessible only from a constructor and having no setter at all becomes important if you try writing a property through reflection.

Upvotes: 5

Yosi Dahari
Yosi Dahari

Reputation: 6999

Either you declare a private member:

private string _image;

Or a public property. When you declare a property, the getter and setter have their own privacy modifiers (i.e protected/public/private/none). For example:

public string Image { get; protected set; }

Upvotes: 0

Related Questions