0

I started studying C# a while back, and I always heard that if I do not have the size of the array, I should always choose list, because arrays can't be initialized without the size.

That being said, I have tried to instance a new array with no size value, and it just works.

string Input = "1-2-3";
string[] Lista = new string[] { };
Lista = Input.Split('-'); 
for(int i = 0; i < Lista.Length; i++)
{
    Console.WriteLine(Lista[i]);
}

Output: 1 2 3.

Do I really have to choose list over array, or it is an outdated concept?

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • Is it wrong to use it as I did in the example? – Nathan David Sep 04 '20 at 15:59
  • 2
    Indeed, you create an array of size 0, which you then throw away when you create a new one (the output of string.Split is an array) – oerkelens Sep 04 '20 at 15:59
  • List is a wrapper around an array of T. It's just there to manage the complexity of using the array to store T in it. (resize, copy, etc). – MikeJ Sep 04 '20 at 16:12

2 Answers2

5

Arrays can't be initialized without a size. When you did string[] Lista = new string[] { };, you created an empty string array. If you did string[] Lista = new string[] { "Hello", "World" };, you'd have created an array of two strings. The size is implied from the contents of the initialization list in {...}.

When you do Lista = Input.Split('-'); later, you replace the original empty array with the new array that comes from Input.Split().

If you want an array into which you can add / remove elements, use a List<>

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
2

Your example above is wrong.

When you do Lista = Input.Split('-'), you overwrite the old array (empty one) with a new one that has 3 items.

In order for you to resize an array you have to do the following:

string[] Lista = new string[] { "str1", "str2" };
// Resize array
Array.Resize<string>(ref Lista, 3);
// Set value for new elements
Lista[2] = "str3";

Be careful, based on the MS documentation (Array) we have the following:

This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one. array must be a one-dimensional array.

As such I would be extremely careful to use such operation as it is CPU intensive. Your best alternative is to use a List.