0

I am implementing a Binary Search Tree and cannot decide if it would be good practice to constrain the generic type of the tree to a comparable item, i.e. IComparable<T>. Or, to just use the default comparer, i.e. Comparer<T>.Default. To me they are functionally the same and they both provide a method to sort with.

Can anyone offer any advice as to why I would choose one or the other?

  • I'd recommend avoiding IComparable<T> and simply require a Func<T, T, int> comparer as a parameter to the tree's constructor. – David Arno Jul 4 at 14:35
2

Avoid adding generic type constraints where possible since these have to be repeated in every generic function that references your type even if the constraint is not relevant to the operation e.g.

public IEnumerable<T> Leaves<T>(BST<T> tree) where T : IComparable<T> { ... }

Using IComparer<T> also allows different comparison operators to be used without needing to create newtype wrappers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.