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 kaka24fan · Feb 23, 2015 at 05:36 PM · scriptingbasicsclassoperatorcustom class

[C#] custom class keys in a dictionary, overloading == etc.

Hello :)

I made a custom class iVector2 which is just a Vector2 but with ints instead of floats. I know a bit about overloading operators, but just the super basic basics.

I'm using a dictionary, the keys of which are iVector2s. I got an error "key not present in dictionary" somewhere where I was sure it shouldn't appear. I assumed it was because I didn't overload an operator ==. But once I did this I got the following warnings:

`iVector2' defines operator == or operator != but does not override Object.Equals(object o)

`iVector2' defines operator == or operator != but does not override Object.GetHashCode()

Ok, so first of all I'd like to know if my reasoning was correct and this error with the keys could have been caused by this or not. I'd also like to know how to get rid of those warnings and what this Object.Equals is. Does it have something to do with interfaces like IComparable (which I know nothing about)?

Thank you very much, have a nice day.

Code:

     public int x;
     public int y;
 
     public iVector2()    {
         x = 0;
         y = 0;
     }
 
 
     public static iVector2 operator ==(iVector2 i1, iVector2 i2) {
     return ((i1.x == iVector2.x) && (i1.y == i2.y));
     }


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 fafase · Feb 23, 2015 at 06:16 PM

The following is more or less the standard way:

     public override bool Equals(object o)
     {
         if (o is iVector2)
             return Equals((iVector2)o);
         else
             return base.Equals(o);
     }

     public bool Equals(iVector2 vec)
     {
         if (vec == null)
             return false;
         if (this.x == vec.x && this.y == vec.y)
             return true;
         else
             return false;
     }

     public static bool operator ==(iVector2 v1, iVector2 v2)
     {
         if (Object.ReferenceEquals(v1, v2))
         {
             return true;
         }
         if (v1 == null || v2 == null)
         {
             return false;
         }
     }

     public static bool operator !=(iVector2 v1, iVector2 v2)
     {
         if (Object.ReferenceEquals(v1, v2))
         {
             return false;
         }

         if (v1 == null || v2 == null)
         {
             return true;
         }

         return !((v1.x == v2.x) && (v1.y == v2.y));
     }

     // this implementation is not necessary
     // Only the override is
     public override int GetHashCode()
     {
             int hash = 17;
             // Suitable nullity checks etc, of course :)
             hash = hash * 23 + x.GetHashCode();
             hash = hash * 23 + y.GetHashCode();
             return hash;
     }

C# requires that if you override the equal sign then it wants some other override to secure that you would not misuse the opposite. This is how the language is made.

Now for your dictionary issue, you would have to show the code you use to fill the dictionary (where you do dict.Add(key, value);)

Comment
Add comment · Show 4 · 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 kaka24fan · Feb 23, 2015 at 06:39 PM 0
Share

Oh boy, I'll have to learn something about all this and then I will return to this answer of yours, for which I thank you. But for now, could you, please, also answer this:

"I can see that the Vector2 that Unity provides stores floats and I wasn't sure if it wouldn't cause any problems if I decide to use Vector2's fields to store something that must be an int (like an index for an array etc.). Do I need to cast v.x to (int) everytime or not? Cheers"

Thanks.

If you think that the dictionary-keys error appears because I did something wrong with filling the dictionary, it's a simple enough problem for me to double-check the code and handle it myself. Thanks.

avatar image fafase · Feb 23, 2015 at 06:52 PM 1
Share

Consider this:

 Vector2 vec = new Vector2(2.0001, 2.9999f);
 int x = (int)vec.x;
 int y = (int)vec.y;

issue here is that your vector is closer to (2, 3) but what you will get is (2, 2) since casting just remove the floating part.

Also, I am not sure you can actually rely on them since float are not exactly what they are, I mean when you think you have a 2.00, it is possible that it is stored as 1.9999999999997 due to the fact that float ing point value are stored as

  x * 10^y 

so it might not be exactly the value, just real close.

So there could be a chance that 2 is stored as 1.9999999999999 which in turn becomes 1 when cast to int. (Not sue though)

Now you can use use $$anonymous$$athf.Round to fix that issue, this would depend on what you are trying to achieve.

avatar image kaka24fan · Feb 23, 2015 at 07:01 PM 0
Share

No, no, that's not the problem, cause I will only be storing ints in them and using them as ints. All I wanted to know was if the casting would be necessary every time, but you know what? I can check that myself, so don't bother. Thanks for help, have a nice life :)

avatar image Jessespike · Feb 23, 2015 at 07:03 PM 1
Share

floats can represent ints with accuracy. http://cottonvibes.blogspot.ca/2010/08/32bit-floats-integer-accuracy-and.html

@kaka24fan Casting shouldn't be a problem, but if you're using your class to represent array indices, that's O$$anonymous$$ too. I thought maybe you were using it for transform positioning, rotation, scale, etc.

avatar image
1

Answer by Jessespike · Feb 23, 2015 at 05:50 PM

Should return a bool. Also don't need a static inside the function.

 public static bool operator ==(iVector2 i1, iVector2 i2) {
     return ((i1.x == i2.x) && (i1.y == i2.y));
 }

http://www.dotnetperls.com/operator

If you're writing this code for practice, then that's fine. But if you're trying to optimize the current vectors or something for your project, I would recommend that you don't and just use the Unity vectors as-is.

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 kaka24fan · Feb 23, 2015 at 06:01 PM 0
Share

I can see that the Vector2 that Unity provides stores floats and I wasn't sure if it wouldn't cause any problems if I decide to use Vector2's fields to store something that must be an int (like an index for an array etc.). Do I need to cast v.x to (int) everytime or not? Cheers

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

21 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

Related Questions

why do I need to type variables classes? 2 Answers

Script throwing error Operator '==' cannot be used with a left hand side of type System.Object and right hand side of type Controller 1 Answer

how to make public variables unique to the gameobject it is attached to? 1 Answer

Getting a custom class to contain a certain script. 1 Answer

How can I make a list of Classes or Scripts? 3 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