• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Olgo · Jul 18, 2013 at 04:57 PM · errortypecasting

What is the difference between "as" and (typecast)

Hey guys, I was wondering why I would get an error with the following code (specifically the last line):

 string[] races = Enum.GetValues(typeof(Race)) as string[];
 string randomRace = races[UnityEngine.Random.Range(0, races.Length)];
 characterRace = (Race) Enum.Parse( typeof( Race ), randomRace );

but not get an error with this code:

 string[] races = Enum.GetValues(typeof(Race)) as string[];
 string randomRace = races[UnityEngine.Random.Range(0, races.Length)];
 characterRace = Enum.Parse( typeof( Race ), randomRace ) as Race;

I thought they were both ways of typecasting / performing the same task, however, the first code produces an error saying "The 'as' operator cannot be used with a non-nullable value type `Character.Race'"

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by homer_3 · Jul 18, 2013 at 06:27 PM

Did you switch your code around by mistake? The 2nd should give you that error, not the 1st. As tries to cast it. If it can't, null is returned. If null isn't a valid value for your storage type, you get that error. Null is not a valid value for an enum.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Olgo · Jul 18, 2013 at 06:48 PM 0
Share

Thanks!

Yes, you're correct. I must have pasted the wrong parts in the wrong message. I won't change it now cuz then it will confuse people when they read this in the future.

So why does the (enum) typecast work? that won't ever return null?

avatar image homer_3 · Jul 18, 2013 at 07:18 PM 0
Share

It's not so much that a typecast doesn't return null, it's that your dest var doesn't accept null. Enum.Parse doesn't return null. It'll just throw an exception on error. But the typecast won't auto catch that exception and return null ins$$anonymous$$d like as would. It's still possible to typecast a null object to something else. But since that object is nullable, you wouldn't be allowed to assign it to another non-nullable type like an enum.

avatar image
0

Answer by Bunny83 · Jul 18, 2013 at 07:13 PM

Like homer already said: The as-cast only works with reference types.

The fundamental difference is:

c-style typecast

  • Can cast any type, so no matter if it's a reference type or a value type

  • If the given variable / value can't be casted into the target type this cast will throw an InvalidCast exception and terminate your function unless you catch the exception with a try-catch block

    as typecast

  • Can only be used on reference types, so it won't work on structs, enums, ints, floats, ...

  • If this cast fails it will not throw an exception but instead return null. Since null can only be assigned to reference or nullable types this cast does only work on reference types.

Note: The as cast can be handy when you have a variable and want to test it for a specific type. However after the cast you can't determine if the cast failed or if the given value already was null.

Example:

     BoxCollider col = GetComponent(typeof(Collider)) as BoxCollider;

if col is null this gameobject either don't have any collider or it has one, but it's not a BoxCollider

This line:

     BoxCollider col = (BoxCollider)GetComponent(typeof(Collider));

will throw an exception if the collider is not a BoxCollider. If it is a BoxCollider it is casted correctly. If there is no Colider at all col will be null since GetComponent returned null.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Olgo · Jul 18, 2013 at 07:15 PM 0
Share

thanks, that's helpful. I've been trying to find a complete explanation but I didn't know what to call the c-style typecast.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

17 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Dynamic array length problem.Why my code generate error? 1 Answer

CommandInvokationFailure: Failed to re-package resources 1 Answer

Metadata error importing unityPackage 0 Answers

Blender Imported .FBX Animations Showing as Read Only 2 Answers

I have a code that let me recenter at Xaxis. 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges