Type (cast) or "as"?

Hi, just as part of my learning journey, I try many things to test.
Here I tried:

Weapon weapon = Resources.Load<Weapon>(defaultWeaponName);
Weapon weapon = (Weapon)Resources.Load(defaultWeaponName);
Weapon weapon = Resources.Load(defaultWeaponName) as Weapon;

And they all work, so… is there a good and a bad way?
Or maybe all those cast don’t work in any situations?

(By the way, sorry for my english, I am french and try to do my best)

M. D.

There is a slight difference between (cast) and “as”

When you cast like this

Weapon weapon = (Weapon)Resources.Load(defaultWeaponName);

and the resource being loaded does not exist or have a Weapon component, C# will throw an exception.
But when you cast like this

Weapon weapon = Resources.Load(defaultWeaponName) as Weapon;

C# will not throw an exception, but your weapon variable will be null
Using this

Weapon weapon = Resources.Load<Weapon>(defaultWeaponName);

Will also return null if the resource cannot be found, or if there is no Weapon component on it.

According to the Unity documentation, Unity does the conversion for you and judging by the result, it probably uses “as”.

In general, the usage is up to you. If you want an exception, use (cast). If you expect possible nulls, use “as”.

Note that structs cannot be cast using “as” because they cannot be null, but in the case mentioned above, you will not be casting structs.

1 Like

Thank you for the response.

So, I think I’ll use the <T> when it exists so I can check for a null return.

M. D.

Learn something every day.

Thanks for putting up this explanation.

Just to throw some extra lesson into the mix (and combine it with checking for the null), you can also use

if(Resources.Load(defaultWeaponName) is Weapon weapon)
{
    /// Any use of weapon within this code block -=guarantees=- 
   /// That weapon is a valid weapon.  
}
3 Likes

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

Privacy & Terms