((ArrayList)list).Sort();

Within minutes of posting a link to Code Blog, someone submitted the following solution...

    public IList Sort(IList list)
    {
        ((ArrayList)list).Sort();
        return list;
    }

This is certainly the simplest possible solution to the problem (in true XP style).  But in my tests I didn't intend this to work!  In fact at one point I was passing an array of doubles (which implements IList) to stop this kind of 'cheating'.  Unfortunately passing an array is open to a similar kind of abuse.

What is the easiest way to restrict the casting of an object?  I've revised the tests to use a class called RestrictedTypeProxy.  I am using it as follows to restrict the interface my ArrayList object is exposing...

            ArrayList arrayList = new ArrayList();
            RestrictedTypeProxy proxy = new RestrictedTypeProxy(arrayList, typeof(IList));
            IList list = (IList)proxy.GetTransparentProxy();

You can also pass any number of MarshalByRefObjects or interfaces.  For example...

            RestrictedTypeProxy proxy = new RestrictedTypeProxy(myOb, typeof(MBRO), typeof(IList), typeof(IDisposable));

You can see how it's implemented by scrolling to the bottom of the page here (oops, not any more).  I will need to use permalinks for historic challenges.  If you still want to see the code, it looks like Fabrice has found a way!

1 Comment

Comments have been disabled for this content.