Coding Equals Operator
-
Hi, Im just wondering, how do you write the equals operator in C#. Im slightly confused about the syntax. For example in C++ for a vector :
class vector{ private: float m_x; float m_y; float m_z; public: vector(x,y,z): m_x(x),m_y(y),m_z(z); vector(): m_x(0),m_y(0),m_z(0); ~vector(); bool operator==(Vector v) { if (this == v) return true; else return (m_x == v.m_x && v.m_y && v.m_z); } }
I know its got something to do the Equals Function and Reference Equals Method. How do you test to see if its the same instance? Many Thanks in advance ;) Tom -
Hi, Im just wondering, how do you write the equals operator in C#. Im slightly confused about the syntax. For example in C++ for a vector :
class vector{ private: float m_x; float m_y; float m_z; public: vector(x,y,z): m_x(x),m_y(y),m_z(z); vector(): m_x(0),m_y(0),m_z(0); ~vector(); bool operator==(Vector v) { if (this == v) return true; else return (m_x == v.m_x && v.m_y && v.m_z); } }
I know its got something to do the Equals Function and Reference Equals Method. How do you test to see if its the same instance? Many Thanks in advance ;) TomTom, The following pages from the .NET Framework General Reference should be of help: Guidelines for Implementing Equals and the Equality Operator (==)[^] and Implementing the Equals Method[^]
- Nick Parker Microsoft MVP - Visual C#
My Blog | My Articles -
Tom, The following pages from the .NET Framework General Reference should be of help: Guidelines for Implementing Equals and the Equality Operator (==)[^] and Implementing the Equals Method[^]
- Nick Parker Microsoft MVP - Visual C#
My Blog | My ArticlesThanks Nick, Much Appreciated. Its just that in C++ you would use the this statement and check against the type on the right. I was just wondering if ReferenceEquals and Equals use the same kind of technique deep down in the CLR thats all. But as for implementing it, you've hit the nail on the head. Many Thanks :laugh:
-
Hi, Im just wondering, how do you write the equals operator in C#. Im slightly confused about the syntax. For example in C++ for a vector :
class vector{ private: float m_x; float m_y; float m_z; public: vector(x,y,z): m_x(x),m_y(y),m_z(z); vector(): m_x(0),m_y(0),m_z(0); ~vector(); bool operator==(Vector v) { if (this == v) return true; else return (m_x == v.m_x && v.m_y && v.m_z); } }
I know its got something to do the Equals Function and Reference Equals Method. How do you test to see if its the same instance? Many Thanks in advance ;) TomYou can also check the following thread: Semantics of Object.Equals(object)[^].
----------------------------- In just two days, tomorrow will be yesterday.