I am trying to implement a Binary Search Tree in C# using generics, but I have no idea how to implement the IComparable
interface. I cannot compare generic type T so I don't know how to implement CompareTo()
function.
Here is the code:
public class BSTNode<T> : IComparable<BSTNode<T>>
{
public T Data { get; set; }
public BSTNode<T> LeftChild { get; private set; }
public BSTNode<T> RightChild { get; private set; }
...
}
When trying to implement public void Insert(BSTNode<T> node)
, I need to compare Data
property, but I get an error saying I cannot compare generic types T.
I tried to implement the IComparable interface but in the CompareTo function, it's the same you cannot compare to T error. Any ideas how I can fix this?
If you add a constraint to your generic type, that will work.
public class BSTNode<T> : IComparable<BSTNode<T>> where T : IComparable<T>
{
public T Data { get; set; }
public BSTNode<T> LeftChild { get; private set; }
public BSTNode<T> RightChild { get; private set; }
public int CompareTo(BSTNode<T> other)
{
return this.Data.CompareTo(other.Data);
}
}
What you need is a generic type constraint:
public class BSTNode<T> : IComparable<BSTNode<T>>
where T : IComparable<T>
That will let you call CompareTo
on Data
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.