Comparison in C#: operator '<' cannot be applied to operands of type 'T' and 'T'

c#, generics

Solution

You should add a constraint such that T must implement `IComparable<T>` and then use that:

public class BinaryTree<T> where T : IComparable<T>
{
    public void AddNode(T data)
    {
        BinaryTreeNode<T> node = new BinaryTreeNode<T>(data);
        BinaryTreeNode<T> temp = root;

        if (temp.Value.CompareTo(node.Value) < 0)
        ...

An alternative is to pass in an `IComparer<T>` and use that:

public class BinaryTree<T> where T : IComparable<T>
{
    private readonly IComparer<T> comparer;

    public BinaryTree(IComparer<T> comparer)
    {
        this.comparer = comparer;
        ...
    }

    public void AddNode(T data)
    {
        BinaryTreeNode<T> node = new BinaryTreeNode<T>(data);
        BinaryTreeNode<T> temp = root;

        if (comparer.Compare(temp.Value, node.Value) < 0)

This is the closest you can get to guaranteeing a "<" operator - overloaded operators are static, and there's no way of constraining a type argument to require it.

Problem

I have created a `BinaryTreeNode<T>` class and then creating `Add(T data)` method for `BinaryTree<T>` class. When I try to compare Values of objects compiler says: operator '<' cannot be applied to operands of type 'T' and 'T'. Example: ``` public void AddNode(T data) { BinaryTreeNode<T> node = new BinaryTreeNode<T>(data); BinaryTreeNode<T> temp = root; if (temp.Value < node.Value) // **PROBLEM HERE** ... ``` I'm using VS08 Express Edition.

Original source