Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Using a loop for insert elements in a array

How do you use a loop to insert values into a string array


  • JobJob Administrator

    An array in C# is immutable meaning inserting new values isn't possible. Look at lists:

  • LeMorrowLeMorrow Member

    Hey, C# arrays are not immutable. It's very possible to set the values of an array. You cannot increase the size of an array, but you can insert new values. For example:

    var words = new string[5];
    for(var i = 0; i < words.Length; i++)
        words[i] = "Hello";

    This would set all 5 strings in the array to "Hello".

    However, if you don't know how big your array is and want to add more items to the array, then you want a List just like Job mentioned.

  • XeramianXeramian Member

    You can use the function of Lists, List.toArray() to get an array from a list if you so please.

  • YasahiroYasahiro Member

    Arrays are not immutable, they are fixed sized. Immutable implies the elements can't be modified - which they can. You just cannot add/remove elements.

  • Definitely use a List<T> any time you want to add/remove data, since resizing arrays is expensive. If you know the data is fixed length, and you want to micro-optimise for some very specific reason (after benchmarking), then an array may be useful.

    List<T> offers a lot more functionality than an array (although LINQ evens it up a bit), and is almost always the right choice.

    More on C# List :

Sign In or Register to comment.