Comparison of common fields

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?

+3
source share
1 answer

Do you mean:

 bool equal = EqualityComparer<T>.Default.Equals(val1,val2); 

This works with IEquatable<T> (for T : IEquatable<T> ) and then returns to object.Equals .

There is also Comparer<T>.Default for comparing inequalities (larger / smaller):

 int delta = Comparer<T>.Default.Compare(val1,val2); 

Otherwise, T : IComparable<T> or T : IComparable .

By the way, Type should just use the regular reference comparative code provided by object.Equals , so it should just work fine with the above.

+6
source

All Articles