views:

62

answers:

1

I am crafting a nested inner class within a generic class and I'm unsure if I'm writing this properly. Is there anything glaringly wrong here?

Here's the code:

public class Foo<T> where T : IComparable<T>
{
    protected class Bar : IComparable
    {
        private KeyValuePair<T, string> _keyval;

        public Bar(KeyValuePair<T, string> kv)
        {
            _keyval = kv;
        }

        public int CompareTo(object obj)
        {
            T comparing = (T)obj;
            return _keyval.Key.CompareTo(comparing.key);
        }
    }

    private List<Bar> _bars;

    public Foo()
    {
        _bars = new List<Bar>();
    }

    public void AddKeyValInOrder(KeyValuePair<T, string> kv)
    {
        Bar toAdd = new Bar(kv);

        int positionToAddAt = _bars.BinarySearch(toAdd);
        if (positionToAddAt < 0)
            positionToAddAt = positionToAddAt ^ -1;

        _bars.Insert(positionToAddAt, toAdd);
    }
}
+2  A: 

Firstly, note that if you don't need duplicates, SortedList<T> may be helpful.

The List<Bar> is going to want to compare Bar instances, so your comparison needs to work on Bar (most easily enforced by implementing IComparable<Bar>:

protected class Bar : IComparable, IComparable<Bar>
{
    private KeyValuePair<T, string> _keyval;

    public Bar(KeyValuePair<T, string> kv)
    {
        _keyval = kv;
    }
    public int CompareTo(Bar other)
    {
        return _keyval.Key.CompareTo(other._keyval.Key);
    }
    int IComparable.CompareTo(object obj)
    {
        return CompareTo(obj as Bar);
    }
}
Marc Gravell