Rich Newman

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.

            // 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)


    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;
                return value.CompareTo(otherValue);

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


  1. Thanks a lot Rich.Gives me a lot of clarity.

    Comment by Srinivas Donavalli — February 9, 2010 @ 7:02 am

  2. Thank Rich. The way you are explaining making easy to the developers to digest the concept.

    Comment by Hari — April 21, 2011 @ 6:08 am

RSS feed for comments on this post. TrackBack URI

Leave a Reply

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

You are commenting using your 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

Create a free website or blog at

%d bloggers like this: