Using Generics To See If A List Is Ordered.

I had some pretty simple code that checked if an array of integers was in ascending order.  I needed to check a second list to see if it was also in ascending order.  The only problem was that is was an array of doubles.  The logic is identical for both lists.  The only difference is the type of data acted on.  This is where generics shine!

I pulled the old code into its own static method and used generics so I could use it on any array of objects that are comparable (implement IComparable):

private static bool IsAscending<T>(T[] values) where T : IComparable
{
    for (int i = 0; i < values.Length - 1; i++)
    {
        if (values[i].CompareTo(values[i + 1]) > 0)
            return false;
    }

    return true;
}

Technorati tags: ,

6 Comments

Comments have been disabled for this content.