C# - ArrayList question

Hi, I’m in the process of looking over another person’s code and found a line that I don’t understand.

Missile missileObj = (Missile)objectsList[0];

Missile is a class that creates a new missile object (taking in Direction, Transform).
objectsList is an arrayList of all the missile objects that currently exist.

My question is why after the ‘=’ there is another reference to the missile class? Is this some kind of C# specific shorthand?

Hello :slight_smile:

In both Javascript and C# in Unity, it is sometimes necessary to explicitly specify the type of an object. In other cases it is nessecary to convert between types. Both of these processes are called Casting.
In most cases casting is done implicitly, like assigning a float value to an int type variable.
But you can also explicitly cast types:

//Implicit casting
int foo = 0.0;

//Explicit casting
int foo = (int)(0.0);
//or
int foo = 0.0 as int;

The same goes for any other type.
In your case you have an array. An array holds object’s of type object. Meaning it can be anything.
But your variable is of a specific type, so it is good to explicitly cast it, but it is not necessary.

Also note that Explicit casting is always faster than implicit. It’s the main reason why:

Missile obj = GetComponent(typeof(Missile)) as Missile;
//is faster than
Missile obj = GetComponent(Missile)

Hope this helps,
Benproductions1

It is a type casting.

Have a look at this

Suppose that you have a hierarchy class like that :
class A is parent of class B.

It is used when you know that an instance of A is in fact an instance of B. The type casting is useful here if you want to use some methods defined in the class B for example.