Property that is set only within protected constructor

a public method used to retrieve the content of a private property
methods cannot be made private
properties are used to protect the fields of the class true or false
protected property c#
c# protected constructor in abstract class
access modifiers in java
typescript protected
private methods in javascript es6

I have following class, and wondering if declaring ListOfItems as public with a private setter is a proper way (from the OOP best practice point of view).

public abstract class Game
{
    public List<int> ListOfItemss { get; private set; }

    protected Game()
    {
    }

    protected Game(string gameInput)
    {
        ListOfItems = new List<int>();
        var gameParser = new GameParser();
        ListOfItems = gameParser.ParseGameInputString(gameInput);
    }

    public abstract int Bowl(int items);
}

Or should I made it via private field i.e.

public abstract class Game
{
    private List<int> _listOfItems;

    public List<int> ListOfItemss 
    {
            get { return _listOfItems; }
            private set { _listOfItems = value; }
        }

    protected Game()
    {
    }

    protected Game(string gameInput)
    {
        ListOfItems = new List<int>();
        _listOfItems = new List<int>(); 
        var gameParser = new GameParser();
        _listOfItems = gameParser.ParseGameInputString(gameInput);
    }

    public abstract int Bowl(int items);
}

    -

Updated based on the suggestions: Based on the suggestions below, here is the code I'm think to have in the final version:

public abstract class Game
{
    public IReadOnlyCollection<int> ListOfItems { get; } = new List<int>();

    protected Game()
    {
    }

    protected Game(string gameInput)
    {
        var gameParser = new GameParser();
        ListOfItems = gameParser.ParseGameInputString(gameInput);
    }

    public abstract int Bowl(int items);
}

Remove the setter (which effectively makes it private to constructors). As Rufus has pointed out, if you don't want this list modifying outside the class, don't expose it as a list. Also, you allow the construction of a Game with a null ListOfItemss. I'd make that default constructor initialise the list, like the other c'tor does. This makes them consistent and avoids nasty null reference exceptions if you try to access game.ListOfItemss:

public abstract class Game
{
    public IEnumerable<int> ListOfItemss { get; } = new List<int>();

    protected Game()
    {
    }

    protected Game(string gameInput)
    {
        var gameParser = new GameParser();
        ListOfItemss = gameParser.ParseGameInputString(gameInput);
    }

    public abstract int Bowl(int items);
}

Private and protected properties and methods, In object-oriented programming, properties and methods are split into two In many other languages there also exist “protected” fields: accessible only from inside the class and the amount of water inside constructor(power) { this.power = power; For instance, we don't want anyone to set it below zero. Property 'name' is protected and only accessible within class 'Person' and its subclasses. A constructor may also be marked protected. This means that the class cannot be instantiated outside of its containing class, but can be extended.

You can just remove the setter : public List<int> ListOfItemss { get; }

Edit : As mentionned in the comments, you can get more infos about the difference between public List<int> ListOfItemss { get; } and public List<int> ListOfItemss { get; private set; } here

820 – A Protected Constructor Allows a Subclass to Create Instances, You can declare a constructor as private to prevent client code from still be able to create a subclass, you can make a constructor protected. public double FeistyFactor { get ; set ; }. // Implicitly invokes default constructor in base class C# 6.0 – Initializing Read-Only Auto-Properties from Constructors� For more information, see Set Priority for Matching Partial Property Names. SetAccess. enumeration. default = public. public — unrestricted access. protected — access from class or subclasses. private — access by class members only (not from subclasses) immutable — property can be set only in the constructor.

Frankly, you shouldn't be providing external access to that list at all, this violates encapsulation. Even though the property is declared IReadOnlyList<int>, there's nothing stopping someone from doing (List<int>)game.ListOfItemss. Private setter or not doesn't really matter, as long as you're limiting access to the internals. If you need to access items of your list externally, expose it through controlled methods such as an indexer.

class Option0
{
    private readonly List<int> items;
    public int this[int index] => this.items[index];
}

Only your class or perhaps derived classes should be allowed access to this list.

With that being said, if you want to expose it as a truly read only list, expose the read only view of it only.

class Option1
{
    private readonly List<int> items;
    public IReadOnlyList<int> Items => items.AsReadOnly();
    public Option1()
    {
        this.items = ...;
    }
}

class Option2
{
    private readonly List<int> items;
    public IReadOnlyList<int> Items { get; }
    public Option2()
    {
        this.items = ...;
        this.Items = this.items.AsReadOnly();
    }
}

Visibility Modifiers, Classes, objects, interfaces, constructors, functions, properties and their setters can have visibility modifiers. There are four visibility modifiers in Kotlin: private , protected , internal and public . private set // setter is visible only in example.kt Until now we were only using public properties and methods. Private: accessible only from inside the class. These are for the internal interface. In many other languages there also exist “protected” fields: accessible only from inside the class and those extending it (like private, but plus access from inheriting classes).

Access Modifiers in Java, Simply put, there are four access modifiers: public, private, protected and When we don't use any keyword explicitly, Java will set a default access to a given class , method or property. Any method, property or constructor with the private keyword is privateMethod(); // available in the same class only. }. A protected member is accessible within its class and by derived class instances. For a comparison of protected with the other access modifiers, see Accessibility Levels. Example. A protected member of a base class is accessible in a derived class only if the access occurs through the derived class type. For example, consider the following code

Abstract Property In Base Class To Force Programmer To Define It , I guess the "correct" way to do this is to have a protected constructor on the base class which requires the state name as a parameter. public abstract class State� A read-write property named Hours allows the customer to specify the time interval in hours. Both the get and the set accessors perform the necessary conversion between hours and seconds. In addition, the set accessor validates the data and throws an ArgumentOutOfRangeException if the number of hours is invalid.

Handbook - Classes, This calls into the constructor we defined earlier, creating a new object with the What's more, before we ever access a property on this in a constructor body, we of class 'Person' is protected and only accessible within the class declaration. If the only argument passed to the Array constructor is an integer between 0 and 2 32-1 (inclusive), this returns a new JavaScript array with its length property set to that number (Note: this implies an array of arrayLength empty slots, not slots with actual undefined values).

Comments
  • Both are the same thing - the only difference is that you control the private field in the second instance. You should implement either - the good thing is that if you implement it as a property and not a field (which is either of the above methods) you are able to adjust the implementation of the property without breaking other code/refactoring.
  • FYI, you don't need to set it to a new list when you immediately set it to something else. And even worse in the second one where you set it to two new lists before setting it to it's final value.
  • Yeah and as the posted answer says - if you want the assignment to be in the constructor and it's never going to be anywhere else in the code you can just make it readonly by removing the setter. You can still add items to the list, you just can't assign a new list.
  • No, and that's the point RufusL and I are making.
  • Then returning a ReadOnlyCollection<int> instead of List<int> would be the way to go. Ideally, you would declare the property as IReadOnlyList<int>.
  • Clients can still modify the list contents in this case
  • As he allows construction without content, that would make sense. If there was just the parameterised constructor, you'd want the public property to be IEnumerable<int>
  • He stated (in the comments) that "I do not want them to modify this list in anyway", so I guess the list gets populated elsewhere from within the class (?).
  • It's an abstract class, so exposing the property to deriving classes likely was the intended means of populating the list. Making the list property protected and having a separate, public read-only list/collection would shore things up.
  • For the difference between the two (with, or without setter) stackoverflow.com/a/36792426/5062791