I have this generic class
public class BinaryTreeNode<T> where T : IComparable
{
public BinaryTreeNode(T value)
{
Value = value;
}
public T Value;
public BinaryTreeNode<T> Right;
public BinaryTreeNode<T> Left;
public BinaryTreeNode<T> Parent;
}
and
public class BinarySearchTree<T> where T : IComparable
{
BinaryTreeNode<T> _root = null;
...
}
and static test method in test class as
public static class TestBST
{
public static BinarySearchTree<T> GetABuiltBST<T>(List<T> valuesToAdd)
{
BinarySearchTree<T> tree = new BinarySearchTree<T>();
foreach (T i in valuesToAdd)
{
tree.Add(i);
}
return tree;
}
}
Now, I get this compile error in this static method
Error 1 The type ‘T’ cannot be used as type parameter ‘T’ in the generic type or method ‘DsLib.BinarySearchTree’. There is no boxing conversion or type parameter conversion from ‘T’ to ‘System.IComparable’
What is going wrong here ? and when to add after generic method name (GetABuiltBST*< T > *) ? Do i even need that ? I put that after method name earlier to get rid of similar error, i didnt go in the detail that time.
If i remove , I get error “The type or namespace name ‘T’ could not be found (are you missing a using directive or an assembly reference?)”
Btw, If i do not constrain T with IComparable then everything was working just fine.
needs a generic constraint that’s strict enough to satisfy:
i.e. you need to add a constraint like this:
As a sidenote, is there any reason why you use
IComparableinstead ofIComparable<T>?And IMO you should not have that constraint on your binary tree class at all. And instead allow the user to pass in an
IComparer<T>. And default toComparer<T>.Defaultwhich in turn usesIComparable<T>if the user doesn’t supply one.