Home > Net >  How to correctly implement this IComparable?
How to correctly implement this IComparable?

Time:10-15

I have problems wit hthe implementation of a generic sorting algorithm.

We need to implement quicksort and selection sort, and a class which should be sortable using these functions. The functions should be generic, and thus work on other classes as well.

I tested the quicksort. It works perfectly on a List. However, when trying to execute it on my own comparable class, it says:

There is no implicit reference conversion from 'SNIP' to 'System.IComparable'

Do you guys have any idea what the problem can be?

Here is my comparable class:

    public class SNIP : IComparable
    { 
        private long lCost { get; set; }

        public SNIP(long lCost)
        {
            this.lCost = lCost;
        }

        public int CompareTo(object obj)
        {
            if (obj == null) return 1;

            SNIP oOtherPlank = obj as SNIP;
            if (oOtherPlank != null)
                return this.lCost.CompareTo(oOtherPlank.lCost);
            else
                throw new ArgumentException("Can only compare SNIPs.");
        }
    }
  

Thanks in advance!

CodePudding user response:

Thanks to @Sweeper, the comparable is now fixed. Like he said, I had to define my class better:

public class SNIP : IComparable<SNIP>
    { 
        private long lCost { get; set; }

        public SNIP(long lCost)
        {
            this.lCost = lCost;
        }

        public int CompareTo(SNIP obj)
        {
            if (obj == null) return 1;

            SNIP oOtherSnip= obj as SNIP;
            if (oOtherSnip!= null)
                return this.lCost.CompareTo(oOtherSnip.lCost);
            else
                throw new ArgumentException("Can only compare SNIPs.");
        }
    }

It is also important to note that this only works when the argument of the CompareTo method is actually of the right class. I tried defining the class as IComparable before, but it didn't work because the argument in CompareTo was set to an object. By changing both the CompareTo header and the class header, the problem is fixed and the sorting now works.

Thanks a lot :-)

CodePudding user response:

You can implement generic IComparable<SNIP>, not IComparable which is very simple: this is always geater than null and if we compare with not null other we should check lCost.

public class SNIP : IComparable<SNIP>
{ 
    private long lCost { get; set; }

    public SNIP(long lCost)
    {
        this.lCost = lCost;
    }

    public int CompareTo(SNIP other) => other is null 
        ? 1
        : lCost.CompareTo(other.lCost);
}

then you can sort: note that since List<SNIP> is generic, the generic IComparable<SNIP> will be used on sorting.

List<SNIP> list = new List<SNIP>() 
{
    new SNIP(5),
    new SNIP(1),
    new SNIP(3),
};

list.Sort();
  •  Tags:  
  • c#
  • Related