Array property syntax in C#

后端 未结 6 625
旧巷少年郎
旧巷少年郎 2020-12-18 23:27

I have a a class that has an integer array property and I am trying to figure out the right syntax for it. The integer array gets instantiated in the class constructor.

6条回答
  •  -上瘾入骨i
    2020-12-19 00:04

    If the number of element in the array is fixed, I would only provide a getter for the array and leave off the setter. You will still be able to assign values to individual elements in the array, but this will prevent someone from swapping the whole array out from under you (or setting it to null. The code would look like this:

    class DemoClass
    {
        public int[] MyNumbers
        { get; private set; }
    
        public DemoClass(int elements)
        {
            MyNumbers = new int[elements];
        }
    }
    

    If the number of elements are not fixed, then you should use a List rather than an array, and then you definitely want a property with no setter.

提交回复
热议问题