June 24, 2007
07:24 PM

Following on from my previous post, I've created some wrappers around System.Collection.Generics.Comparer<T>.Default and System.Collections.Generic.EqualityComparer<T>.Default which return specialised versions for dealing with ValueTypes without boxing.

For the previous example, we can eliminate the boxing like this:

int[] ints = new int[] { 1 };
Array.BinarySearch<int>(ints, 1, Utils.Collections.Comparer<int>.Default);

Or for a Dictionary<K,V>.

new Dictionary<int, int>(Utils.Collections.EqualityComparer<int>.Default);

The code is here.

Update: Actually, it seems Dictionary<K,V> is broken too, since all the methods which take a Key (Add, Contains, TryGetValue, Remove) still end up boxing by checking the key against null.

© Douglas Stockwell 2007
Creative Commons License Unless otherwise specified all "source code" examples are available for use under the Creative Commons Attribution-Noncommercial 3.0 License. Please contact me if you would like more flexible licensing terms.
Messenger Presence