Search code examples
c#javacomparatoricomparable

Java Comparator override equivalent in c#


I want to convert the following class from java to C#:

public class ValueComparator implements Comparator{

    @Override
    public int compare(Object ob1, Object ob2){
        int retval = 0;
        if ( ob1 instanceof DataCol && ob2 instanceof DataCol ){
            DataCol c1 = (DataCol) ob1;
            DataCol c2 = (DataCol) ob2;
            if( c1.value < c2.value ) retval = 1;
            if( c1.value > c2.value ) retval = -1;
        } else {
            throw new ClassCastException("ValueComparator: Illegal arguments!");
        }
        return(retval);
    }    
}

Solution

  • Why not just implement the non-generic IComparer interface directly? That is, the non-generic Java interface converts to the non-generic C# interface:

    public class ValueComparator : System.Collections.IComparer
    {
        public int Compare(object ob1, object ob2)
        {
            int retval = 0;
            if (ob1 is DataCol && ob2 is DataCol)
            {
                DataCol c1 = (DataCol) ob1;
                DataCol c2 = (DataCol) ob2;
                if (c1.value < c2.value) retval = 1;
                if (c1.value > c2.value) retval = -1;
            }
            else
            {
                throw new ClassCastException("ValueComparator: Illegal arguments!");
            }
            return (retval);
        }
    }