I have some common types, for example:
public struct Tuple<T1, T2> { ... } public struct Tuple<T1, T2, T3> { ... } etc.
Theoretically, they should be able to compare themselves with other values โโof the same type, so I can write the following type of code:
List<Tuple<Type, String>> l = new List<Tuple<Type, String>>(); l.Add(new Tuple<Type, String>(typeof(ISomeInterface), "123")); if (l.Contains(new Tuple<Type, String>(typeof(ISomeOtherInterface), "123")) ...
Unfortunately, there was an error in my code, and then the question arises of how to do this correctly.
The error was related to my implementation of CompareTo>, which basically looks like this:
Int32 result = HelperMethods.CompareTwoFields<T1>(_Value1, other._Value1); if (result != 0) return result; Int32 result = HelperMethods.CompareTwoFields<T2>(_Value2, other._Value2); if (result != 0) return result; return 0;
HelperMethods.CompareTwoFields is as follows:
internal static Int32 CompareTwoFields<T>(T field1, T field2) { Int32 result = 0; if (ReferenceEquals(field1, null) != ReferenceEquals(field2, null)) result = ReferenceEquals(field1, null) ? -1 : +1; else if (!ReferenceEquals(field1, null) && field1 is IComparable<T>) result = ((IComparable<T>)field1).CompareTo(field2); else if (!typeof(T).IsValueType) { if (Object.ReferenceEquals(field1, field2)) return 0; else return field1.ToString().CompareTo(field2.ToString()); } return result; }
In the latter case, the if-statement is something that I filled in right now to fix the error, but is this correct?
Basically, how do I compare two type objects? Is there any meaningful comparison for them, except to just convert them to a string and compare?