- Home /
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?
Answer by Benproductions1 · Jun 13, 2013 at 11:30 PM
Hello :)
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
Answer by KiraSensei · Jun 13, 2013 at 11:30 PM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220613104137im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Change value of ArrayList inside another ArrayList 1 Answer
How to "get" an item from an ArrayList? 0 Answers
function returns an arraylist 1 Answer