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)
65 return y == null ? 0 : -1;
70 return Compare ((T) x, (T) y);
72 throw new ArgumentException ();
76 sealed class DefaultComparer : Comparer<T>
78 public override int Compare (T x, T y)
80 // `null' is less than any other ref type
82 return y == null ? 0 : -1;
86 var i = x as IComparable;
88 return i.CompareTo (y);
92 return -i.CompareTo (x);
94 throw new ArgumentException ("At least one argument has to implement IComparable interface");
100 sealed class GenericComparer<T> : Comparer<T> where T : IComparable<T>
102 public override int Compare (T x, T y)
104 // `null' is less than any other ref type
106 return y == null ? 0 : -1;
110 return x.CompareTo (y);
115 sealed class ComparisonComparer<T> : Comparer<T>
117 readonly Comparison<T> comparison;
119 public ComparisonComparer (Comparison<T> comparison)
121 this.comparison = comparison;
124 public override int Compare (T x, T y)
126 return comparison (x, y);