Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • 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 killerhook · Apr 22, 2014 at 03:10 AM · casting

Cannot cast from source type to destination type in C#

Hi, I'm trying to use the code this.

 public static string CreateOptionTooltip(Item item)
     {
         if(item.getEquipable())
         {
             string tooltip = "";
             EquipmentItem equipItem = (EquipmentItem)item;
             for(int i = 0; i < equipItem.optionList.Count; i++)
             {
                 ItemOption option = equipItem.optionList[i];
                 tooltip += option.itemOption.ToString();
                 if(option.optionAmount >= 0)
                     tooltip += "\t+" + option.optionAmount.ToString();
                 else
                     tooltip += "\t-" + option.optionAmount.ToString();
                 tooltip += "\n";
             }
             return tooltip;
         }
         else
         {
             return "";
         }
     }

The EquipmentItem Class is child class of Item like this.

 public class EquipmentItem : Item
 {
        public EquipmentItem()
        {
            //Here is initializing code.
        }
 }

But when I call the method CreateOptionTooltip(Item item) in gaming there is error InvalidCast: Cannot cast from source type to destination type in line EquipmentItem equipItem = (EquipmentItem)item;

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

1 Reply

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

Answer by Benproductions1 · Apr 22, 2014 at 08:02 AM

You can only cast up the inheritance tree, you can't cast down the inheritance tree because not everything is guaranteed to exist.

Say you have a class:

 class Foo {
     int index;
     float position;
 }

And another class:

 class Bar : Foo {
     void Do() {
     }
 }

Now lets say you are given a variable of type Bar. This you can easily cast to a Foo because Bar inherits from Foo, ie. you're casting up the tree. Once you have a Foo from your Bar, everything from Foo still exists in your variable, ie. you have access to index and position.

But what if you have a variable of type Foo. This you cannot cast to a Bar, simply because a Bar can Do(), while a Foo cannot. Therefore your Foo cannot be a Bar, but your Bar can be a Foo.

The same goes for the Finger-Thumb analogy. Think of Foo as a Finger and Bar as a Thumb. Your Thumb is a finger, ie. you can cast your Thumb to a Finger. But not all Fingers are Thumbs, you therefore cannot cast any Finger to a Thumb.

You therefore cannot cast an Item to a EquipmentItem, since not all items are equipment items, but you can cast any EquipmentItem to an Item, since all EquipmentItems are Items.

Comment
Add comment · Show 5 · 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 killerhook · Apr 22, 2014 at 11:07 PM 1
Share

Okay, I understood clearly. But I have one more question. Then how about using List<>? When I learned Java or other program$$anonymous$$g languages, there is List<> Class for the Array of ClassType. With your example, if I made a List<>Foo(Sorry to write the Foo outside of brackeys if I write inside of it, it is blowed up.) arrayFoo, then we can put the Bar Class into arrayFoo. You know, when we get the thing which was Bar Class from the arrayFoo, the type of the thing is Foo because we use List<>Foo. But if I need the specific variable of Bar then we need to cast thing Foo to Bar so that we can use the specific variable of Bar. In this case, I am making inventory system with List<>Item. And EquipmentItem has specific variables like durability or Equip Job Limit. Then how can I access this kinds of variables when I get the Item from List<>Item?

avatar image Benproductions1 · Apr 23, 2014 at 12:34 AM 0
Share

http://msdn.microsoft.com/en-us/library/cc488006.aspx

You have to make sure you have the right type before casting, ie. using the is operator.

avatar image killerhook · Apr 23, 2014 at 04:35 AM 0
Share

Thank you for your help! I really appreciate about your answer for me.

avatar image getyour411 · Apr 23, 2014 at 04:42 AM 0
Share

Nice explanation

avatar image Benproductions1 · Apr 23, 2014 at 06:11 AM 0
Share

@getyour411 thanks ;)

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.

Follow this Question

Answers Answers and Comments

22 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 avatar image avatar image avatar image avatar image avatar image

Related Questions

Problem with type casting from C# to JS 3 Answers

Dynamic Casting during runtime 1 Answer

How do I cast an IntPtr to another class? 0 Answers

Converting to ColliderCast - what's included in the PhysicsWorld and how do I include my own meshes? 0 Answers

Error, class project 1 Answer


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