Michal Počatko Michal Počatko - 29 days ago 8
C# Question

Custom class: Failed to compare two elements in the array

I have a list of abstract Class elements and when I try to sort it I get an exception with a message "Failed to compare two elements in the array"

Abstract Class:

public abstract class Node : IComparable<Leaf>, IComparable<Interrior>
{
public virtual ulong Weight { get; set; }
protected virtual int CompareWeights(Node node)
{
if (this.Weight < node.Weight) return -1;
else if (this.Weight > node.Weight) return 1;
else return 0;
}
public abstract int CompareTo(Interrior node);
public abstract int CompareTo(Leaf node);
}


Derived classes:

public class Interrior : Node
{
public Interrior(byte age, Node left, Node right)
{
Age = age;
Left = left;
Right = right;
Weight = Left.Weight + Right.Weight;
}
public byte Age { get; }
public Node Left { get; }
public Node Right { get; }
public override int CompareTo(Interrior node)
{
var result = CompareWeights(node);
if (result == 0) result = this.Age < node.Age ? -1 : 1;
return result;
}
public override int CompareTo(Leaf node)
{
var result = CompareWeights(node);
if (result == 0) result = 1;
return result;
}
}
public class Leaf : Node
{
public Leaf(byte symbol)
{
Symbol = symbol;
Weight = 1;
}
public byte Symbol { get; }
public override int CompareTo(Interrior node)
{
var result = CompareWeights(node);
if (result == 0) result = -1;
return result;
}

public override int CompareTo(Leaf node)
{
var result = CompareWeights(node);
if (result == 0) result = this.Symbol < node.Symbol ? -1 : 1;
return result;
}
}


Can anybody please tell me what I'm doing wrong here? I want to create List of nodes and call a method sort on it, thank you.

Answer

You don't have an IComparable<Node> on the base. Implement that, and delegate it to the ones you implemented for Interior and Leaf.

Comments