开发者

Sorting non IComparable objects

According documentation:

System.Array.Sort<T> - sorts the elements in an entire System.Array using the System.IComparable generic interface implementation of each element of the System.Array.

Today I 开发者_如何学Godiscover, that this code is compiling without any errors and warnings:

A []arr = new A[10];//A is not inheriting from IComparable !!

//initializing elements of arr
...

System.Array.Sort<A>(arr);

After execution I'm getting run-time error.

So why this code is compiling? I'm not big expert of C#, but I know, that C# generics supporting constraining syntax. Why constraints aren't used for Array.Sort?


In compiles because there's no constraint on T that it has to implement IComparable<T>.

I think the documentation is slightly confusing, because the array elements don't actually have to implement IComparable<T> for the same T as the call. For example, this works fine:

using System;

class Test
{
    static void Main()
    {
        object[] objects = { "d", "b", "c", "a" };        
        Array.Sort<object>(objects);
    }
}

I think it's more sensible to just say that the elements have to be comparable with each other "somehow". For example, this is fine, even though nothing's implementing the generic IComparable interface:

using System;

class A : IComparable
{
    private readonly int value;

    public A(int value)
    {
        this.value = value;
    }

    public int CompareTo(object other)
    {
        // Just cast for now...
        return value.CompareTo(((A)other).value);
    }
}

class Test
{
    static void Main()
    {
        object[] objects = { new A(5), new A(3), new A(4) };
        Array.Sort<object>(objects);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜