Thursday, 20 September 2018

How to solve Operator '==' cannot be applied to operands of type 'T'

In this post we are going to see how to compare a field or property which have type as T Generic. Generally if you try to compare Generic types with ==,!= operator it will results in Operator == or != cannot be applied to operands of Type 'T'

For example:
********************

  public class Node<T>
    {
        private T _data;
        private Node<T> _next;
        private Node<T> _prev;

        public T Data
        {
            get { return _data; }
            set { _data = value; }
        }

        public Node<T> Next
        {
            get { return _next; }
            set { _next = value; }
        }

        public Node<T> Previous
        {
            get { return _prev; }
            set { _prev = value; }
        }

        public Node(T value):this(value,null, null)
        {
           
        }

        public Node(T value, Node<T> next, Node<T> prev)
        {
            this._data = value;
            this._next = next;
            this._prev = prev;
        }
    }


public Node<T> AddBefore(Node<T> element, T value)
   {
            var tempNode1 = new Node<T>(value);
            var tempNode2 = new Node<T>(value);

            if(tempNode1.Data == tempNode2.Data) { 
              
            }
         
   } 


In the above example if you see the line , if(tempNode1.Data == tempNode2.Data) { where we compare the two T type with == operator now this will return a compile time error.

To resolve this error we have to use EqualityComparer

if(EqualityComparer<T>.Default.Equals(tempNode1.Data,tempNode2.Data))

{

}


so the result method will be
public Node<T> AddBefore(Node<T> element, T value)
{
            var tempNode1 = new Node<T>(value);
            var tempNode2 = new Node<T>(value);

            if(EqualityComparer<T>.Default.Equals(tempNode1.Data,tempNode2.Data)) { 
              
            }
         


From this post you can learn how to solve operator '==' cannot be applied to operands of type 'T'