- Home /
Query with C# arrays and List<>
Hi,
Strange question, but I'm new to C# and I'm trying to differentiate between the two blocks of code.
So, this:
public List<Color> shapeColor = new List<Color>();
if(shapeColor.Count > 0)
{
int newColor = Random.Range(0, shapeColor.Count);
renderer.material.color = shapeColor[newColor];
}
And this:
public Color[] shapeColor;
if(shapeColor.Length > 0)
{
int newColor = Random.Range(0, shapeColor.Length);
renderer.material.color = shapeColor[newColor];
}
Both blocks seem to achieve the same thing - selecting a random colour from an array of colours selected in the inspector. My understanding of C# was that you should use List<> if the array of items you're using is not a set length as it will produce errors otherwise. Here, the colours are picked in the Inspector window, so it can't be defined in the code.
I had initially defined the shapeColor array as below:
public Color shapeColor[];
But ran into errors with the rest of the code because of the above. My question is, how is using Color[] any different and is could this cause any difficulties?
Answer by whydoidoit · Apr 28, 2013 at 09:50 PM
Native arrays "[]" are not resizable at run time. Lists are. You should use native arrays if the contents will not change during the execution of the game and Lists otherwise. They are semantically similar but arrays use Length and Lists use Count for the number of items.
Ah! Thanks!
Is there any different between:
public Color shapeColor[];
and
public Color[] shapeColor;
$$anonymous$$y previous experience would have lead me to think that the top way was correct in this example, but it seems to be the other way around?
No the bottom way is right, though I've been known to find myself typing the top way and having to fix it ;)
The point is you are defining a variable called shapeColor so it comes last. Then the type of that variable is an array of Color so you write that as the type. Hence the bottom one is right.
Answer by Loius · Apr 28, 2013 at 09:51 PM
[] array is just a bunch of memory in a row. So it's super-fast to access and super-slow to resize (can't be resized, you have to grab a new chunk of memory and copy the values over).
List is a class which essentially contains a [] array and helper functions to make resizing it less prone to error.
There are no errors for using variable-length [] arrays, you just have to be aware that you're using variable-length arrays.