Inversion of Control in .NET: an example of the use of IComparable

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // WeirdInteger defines a custom sort order where
            // negative numbers are bigger than positive ones.
            WeirdInteger[] ary = new WeirdInteger[7];
            ary[0] = new WeirdInteger(-1);
            ary[1] = new WeirdInteger(1);
            ary[2] = new WeirdInteger(2);
            ary[3] = new WeirdInteger(-2);
            ary[4] = new WeirdInteger(-3);
            ary[5] = new WeirdInteger(3);
            ary[6] = new WeirdInteger(0);

            // Array.Sort is calling the CompareTo method in WeirdInteger
            // repeatedly - control has been inverted here.
            Array.Sort(ary);

            // Expected order is 0,1,2,3 (ascending integers but
            // 'less than' the negative integers) and then -3,-2,-1
            // (ascending negative integers)
            foreach (WeirdInteger i in ary)
                Console.WriteLine(i.ToString());

            Console.ReadLine();
        }
    }

    class WeirdInteger : IComparable
    {
        private int value;
        internal WeirdInteger(int value)
        { this.value = value; }

        #region IComparable Members
        // Sort our integers such that any value less than
        // zero is bigger than a value greater than zero.  Otherwise
        // sort normally.  This means that -1 is the largest possible number.
        public int CompareTo(object obj)
        {
            int otherValue = ((WeirdInteger)obj).value;
            if (value == otherValue)
                return 0;
            else if (value < 0 && otherValue >= 0)
                return 1;
            else if (otherValue < 0 && value >= 0)
                return -1;
            else
                return value.CompareTo(otherValue);
        }
        #endregion

        public override string ToString()
        {
            return value.ToString();
        }
    }
}

2 thoughts on “Inversion of Control in .NET: an example of the use of IComparable

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s