Reputation: 3243
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);
).
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
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:
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
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