Home
Manage Your Code
Snippet: Implementing IEquatable, IComparable, operators and Object overrides For A ValueType (C#)
Title: Implementing IEquatable, IComparable, operators and Object overrides For A ValueType Language: C#
Description: Implementing IEquatable, IComparable, operators and Object overrides For A ValueType Views: 68
Author: Peter Parker Date Added: 4/28/2008
Copy Code  
1 public struct MyValue : IComparable<MyValue>, IEquatable<MyValue>
2    {
3        int theValue;
4        public int CompareTo(MyValue other)
5        {
6            return theValue - other.theValue;
7        }
8
9        public bool Equals(MyValue other)
10        {
11            return CompareTo(other) == 0;
12        }
13
14        public override bool Equals(object obj)
15        {
16            if (!(obj is MyValue))
17            {
18                throw new ArgumentException("Not MyValue type.");
19            }
20            return Equals((MyValue)obj);
21        }
22
23        public override int GetHashCode()
24        {
25            return theValue.GetHashCode();
26        }
27
28        public static bool operator ==(MyValue leftHandValue, MyValue rightHandValue)
29        {
30            return leftHandValue.Equals(rightHandValue);
31        }
32        public static bool operator !=(MyValue leftHandValue, MyValue rightHandValue)
33        {
34            return !leftHandValue.Equals(rightHandValue);
35        }
36        public static bool operator <(MyValue leftHandValue, MyValue rightHandValue)
37        {
38            return leftHandValue.CompareTo(rightHandValue) < 0;
39        }
40        public static bool operator >(MyValue leftHandValue, MyValue rightHandValue)
41        {
42            return leftHandValue.CompareTo(rightHandValue) > 0;
43        }
44        public static bool operator <=(MyValue leftHandValue, MyValue rightHandValue)
45        {
46            return leftHandValue.CompareTo(rightHandValue) <= 0;
47        }
48        public static bool operator >=(MyValue leftHandValue, MyValue rightHandValue)
49        {
50            return leftHandValue.CompareTo(rightHandValue) >= 0;
51        }
52    }
Notes
http://www.bokebb.com/dev/english/1937/posts/193711865.shtml