Generic Comparer

Have you ever had to write a comparer for a specific type, only to be frustrated when you needed to write a second and third comparer for other types? Fear not, a generic comparer can take care of this for you!

/// <summary>
/// Compares two objects of any type.
/// </summary>
/// <typeparam name="T">The type to be compared.</typeparam>
public class GenericComparer<T> : IComparer<T>
{
    // The compare method
    private readonly Func<T, T, int> _compareMethod = null;
/// &lt;summary&gt;
/// The constructor.
/// &lt;/summary&gt;
/// &lt;param name=&quot;compareMethod&quot;&gt;The compare method.&lt;/param&gt;
public GenericComparer(Func&lt;T, T, int&gt; compareMethod)
{
    // Sanitize
    if (compareMethod == null)
    {
        throw new ArgumentNullException(&quot;compareMethod&quot;);
    }

    _compareMethod = compareMethod;
}

/// &lt;summary&gt;
/// Compares two objects.
/// &lt;/summary&gt;
/// &lt;param name=&quot;x&quot;&gt;The first object.&lt;/param&gt;
/// &lt;param name=&quot;y&quot;&gt;The second object.&lt;/param&gt;
/// &lt;returns&gt;Less than 0 if x is less than y, greater than 
/// 0 if x is greater than y, 0 if they are equal.&lt;/returns&gt;
public int Compare(T x, T y)
{
    return _compareMethod(x, y);
}

}

Just pass a method to the constructor that takes 2 objects of type T and returns an int, and you’re all set!

One minute to read

An Overview of Generic Constraints

This is my first post. I hope that it doesn’t suck.

As of .NET 2.0, Microsoft introduced the concept of generics. Generics is a concept that allow you to “template” methods and types such as classes and interfaces in a (generally) type-safe way. Upon compilation, generic type metadata is stored in IL, and JIT’d as you reference the generic method or class with an actual type at runtime. Value types each get their own “copy” of the JIT’d generic code, whereas reference types share a single instance of the code. This is because the generic implementation is identical for reference types – they’re all just pointers.

4 minutes to read