I have a generic BST and a dataItem class to act as a treeNode value.
public class BinarySearchTree<T> : ICollection<T> where T : IComparable { } public class EnglishDictionaryWord : IComparer<EnglishDictionaryWord>, IComparable<EnglishDictionaryWord> { public EnglishDictionaryWord(string word, WordCompareType type) { Word = word; Length = Word.Length; _compareType = type; } public int Compare(EnglishDictionaryWord x, EnglishDictionaryWord y) { if (_compareType == WordCompareType.Length) return new WordLengthComparer().Compare(x, y); else if (_compareType == WordCompareType.Lexical) return new WordLexicalComparer().Compare(x, y); else throw new InvalidOperationException("Unsupported Comparison type"); } public int CompareTo(EnglishDictionaryWord obj) { return Compare(this, obj); } } public class WordLengthComparer : IComparer<EnglishDictionaryWord> { public WordLengthComparer() { } public int Compare(EnglishDictionaryWord x, EnglishDictionaryWord y) { return x.Length - y.Length; } } and similar Lexical comparer class.
Now when I try to use:
BinarySearchTree<EnglishDictionaryWord> _tree = new BinarySearchTree<EnglishDictionaryWord>();
I get a compilation error:
The type "DsLib.EnglishDictionaryWord" cannot be used as a parameter of type "T" in the generic type or method "DsLib.BinarySearchTree". There is no implicit conversion of links from "DsLib.EnglishDictionaryWord" to "System.IComparable".
If I try to do
public class BinarySearchTree<T> : ICollection<T> where T : IComparable<T>
then I get this compilation error about the impossibility of converting a box.
Type 'T' cannot be used as a parameter of type 'T' in a generic type or method 'DsLib.BinaryTreeNode'. There is no conversion of box conversion or conversion of type parameters from "T" to "System.IComparable".
I have 2 questions:
(1). I am confused about the implementation of generics. Can anyone clarify how to fix it? and a general outline to avoid such errors in the future. When to use IComparable<T> and when to IComparable .
(2). Is this comparison template having a comparator inside the dataitem class correct? Because the user will provide a new EnglishWord for insertion into the tree. It can potentially use different comparisons for each word. Then he will destroy the tree.
EDIT: Added BSTNode class code
public class BinaryTreeNode<T> where T : IComparable { public BinaryTreeNode(T value) { Value = value; } public T Value { get; protected internal set; } public BinaryTreeNode<T> Right { get; protected internal set; } public BinaryTreeNode<T> Left { get; protected internal set; } public BinaryTreeNode<T> Parent { get; protected internal set; } public int Height { get; protected internal set; } }