5 // Ben Maurer (bmaurer@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
9 // Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com)
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Runtime.InteropServices;
34 namespace System.Collections.Generic {
36 public abstract class Comparer<T> : IComparer<T>, IComparer
38 static readonly Comparer <T> _default = typeof (IComparable<T>).IsAssignableFrom (typeof (T)) ?
39 (Comparer<T>) Activator.CreateInstance (typeof (GenericComparer <>).MakeGenericType (typeof (T))) :
40 new DefaultComparer ();
42 public abstract int Compare (T x, T y);
44 public static Comparer<T> Default {
51 public static Comparer<T> Create (Comparison<T> comparison)
53 if (comparison == null)
54 throw new ArgumentNullException ("comparison");
56 return new ComparisonComparer<T> (comparison);
60 int IComparer.Compare (object x, object y)
64 return y == null ? 0 : -1;
69 return Compare ((T) x, (T) y);
71 throw new ArgumentException ();
75 sealed class DefaultComparer : Comparer<T>
77 public override int Compare (T x, T y)
79 // `null' is less than any other ref type
81 return y == null ? 0 : -1;
85 if (x is IComparable<T>)
86 return ((IComparable<T>) x).CompareTo (y);
87 else if (x is IComparable)
88 return ((IComparable) x).CompareTo (y);
90 throw new ArgumentException ("does not implement right interface");
96 sealed class GenericComparer<T> : Comparer<T> where T : IComparable<T>
98 public override int Compare (T x, T y)
100 // `null' is less than any other ref type
102 return y == null ? 0 : -1;
106 return x.CompareTo (y);
111 sealed class ComparisonComparer<T> : Comparer<T>
113 readonly Comparison<T> comparison;
115 public ComparisonComparer (Comparison<T> comparison)
117 this.comparison = comparison;
120 public override int Compare (T x, T y)
122 return comparison (x, y);