Best way to “push” into C# array

后端 未结 12 2660
没有蜡笔的小新
没有蜡笔的小新 2021-02-13 14:25

Good day all

So I know that this is a fairly widely discussed issue, but I can\'t seem to find a definitive answer. I know that you can do what I am asking for using a L

12条回答
  •  一个人的身影
    2021-02-13 14:31

    As said before, List provides functionality to add elements in a clean way, to do the same with arrays, you have to resize them to accomodate extra elements, see code below:

    int[] arr = new int[2];
    arr[0] = 1;
    arr[1] = 2;
    //without this line we'd get a exception
    Array.Resize(ref arr, 3);
    arr[2] = 3;
    

    Regarding your idea with loop:

    elements of an array are set to their default values when array is initialized. So your approach would be good, if you want to fill "blanks" in array holding reference types (which have default value null).

    But it wouldn't work with value types, as they are initialized with 0!

提交回复
热议问题