Search code examples
c#listclassreadonly-collection

Make a list readonly in c#


I have this example code. What I want to do is to make it so that the "Nums" value can only be written to using the "AddNum" method.

namespace ConsoleApplication1
{
    public class Person
    {
        string myName = "N/A";
        int myAge = 0;
        List<int> _nums = new List<int>();

        public List<int> Nums
        {
            get
            {
                return _nums;
            }
        }

        public void AddNum(int NumToAdd)
        {

            _nums.Add(NumToAdd);
        }

        public string Name { get; set; }
        public int Age { get; set; }
    }
}

Somehow, I've tried a bunch of things regarding AsReadOnly() and the readonly keyword, but I can't seem to get it to do what I want it to do.

Here is the sample of the code I have to access the property.

Person p1 = new Person();
p1.Nums.Add(25); //access 1
p1.AddNum(37); //access 2

Console.WriteLine("press any key");
Console.ReadLine();

I really want "access 1" to fail, and "access 2" to be the ONLY way that the value can be set. Thanks in advance for the help.


Solution

  • √ DO use ReadOnlyCollection, a subclass of ReadOnlyCollection, or in rare cases IEnumerable for properties or return values representing read-only collections.

    The quote from this article.

    You should have something like this:

    List<int> _nums = new List<int>();
    
    public ReadOnlyCollection<int> Nums
    {
        get
        {
            return _nums.AsReadOnly();
        }
    }