Creating an Array - Array name "State[]" - help me to understand

Hi,
I would need help understanding why when creating the “State” array we called the array “State” (same name of the class this is in) and why we couldn’t name it something like “myStateArray” (something of our own name within the class “State”).
It seems the class name had to be used for the array name in this instance, but I don’t understand why? What am I missing…

  • why the array had to be called the same as the class name?
  • why we can’t use a made-up name (like in the initial example of “oddNumber” array)

Can someone please explain that to me. Thank you

Hi Mirek,

In C#, we create an array by writing the type, which is, for example, State, and by adding [] behind the type name. State[] variableName; is the declaration of a variable of type Array where the array is supposed to contain elements of type State. That’s the C# syntax. Why? Because the C# programmers made it this way.


See also:

2 Likes

Hi Nina,

Firstly thank you for your quick response.

So if I understand this correctly the array “State” in this example has nothing to do with the Class being also named “State”, but rather the actual word State in an array environment is a type of an array.

Just to confirm - my question was fully based on the tutorial video regarding the “Creating an Array”, lecture #26.

If my understanding is correct, I guess I just got confused with the lecture where the word “State” is used multiple times but with different meaning (Class is called State, but also the array is called State etc. that led me to believe these two are linked somehow). I assume it will become more clearer to me further I progress in the tutorial (the tutorial is great btw)

That’s correct. The Array class is a special class in C#. That’s why we have this funny syntax in this special case. We are creating an array of type State where State refers to the class we created earlier.

Try to regard C# and Unity as two different things. That’ll make your life easier.

In C#, we have our State class. It’s a class, nothing else. We do C# stuff with it like, for example, creating an array or objects.

In Unity, we can use our class/script and assign it to an Inspector. Then we automatically get an object of type State (C# side) and a component (Unity side), which we can control via our C# code.

If a game object or a scriptable object has got a name in the Unity Editor, this has nothing to do with C#. Your State object remains a State object in C#, even if you name it “Room 1” or “Kitchen”.

So if Rick mentions “State”, all you have to do it to figure out if he’s referring to your code or something in Unity.

And if that’s too confusing, don’t worry. With time and effort, these concepts will eventually reveal themselves to you. :slight_smile:

2 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms