tags:

views:

64

answers:

2

Is there a way in .NET that I can sort my collection when I do not know what types of objects at run time I will pass to this collection and also by avoiding Reflection.

any thoughts?

+5  A: 

You do need some way of comparing elements. The usual way is to demand IComparable:

class MyCollection<T> where T : IComparable<T>
{
}

or use an IComparer, either for the Sorting method or the constructor:

class MyCollection<T> // where T : IComparable<T>
{
    void Sort(IComparer<T> comparer) 
    {
        if  (comparer.Compare(a, b) > 0) { ... }
    }
}
Henk Holterman
+1  A: 

Why can't you use an ArrayList collection?

ArrayList list = new ArrayList();
list.Add("R");
list.Add("B");
list.Add("G");
list.Sort();
//produces "B","G","R"

list.Clear();
list.Add(100);
list.Add(10);
list.Add(9);
list.Sort();
//produces 9,10,100
jalexiou
Because:List.Add("R");List.Add("B");List.Add("G");List.Add(100);List.Add(new Apple());List.Add(new Orange());
Kieren Johnstone
because they are not always regular types like string, int,etc...most of the times they are objects of the classes I have defined.
BDotA
The implement IComparable<> to the base class (or interface)
jalexiou