Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve Operator '!=' cannot be applied to operands of type 'T' and 'T' [duplicate]

Tags:

c#

generics

This code snippet works as expected for the int type:

public class Test 
{
    public int Value
    {
        get => _Value;
        set
        {
            if (_Value != value)
                _Value = value;
        }
    }
    private int _Value;
}

When int is replaced by the generic T, the compiler complains with:

Operator '!=' cannot be applied to operands of type 'T' and 'T'

Why does this happen and is there a way to solve it?

like image 838
Darf Avatar asked Oct 17 '22 18:10

Darf


2 Answers

using System.Collections.Generic;

public class Test<T>
{
    public T Value
    {
         get => _Value; 
         set
         {
            // operator== is undefined for generic T; EqualityComparer solves this
            if (!EqualityComparer<T>.Default.Equals(_Value, value))
            {
                _Value = value;
            }
         }
    }
    private T _Value;
}
like image 200
user541686 Avatar answered Oct 19 '22 06:10

user541686


T is a type argument and can be a class or a struct, Thus the compiler won't let you perform actions that don't exist both in classes and structs.

structs don't have the == and != by default(but can be added), this is why the compiler complains.

If you use the where keyword to add a constraint to the type argument, the compiler will let you use that type\interface method\operators

constrain T to be a class

public class Test<T> where T : class
{
     public T Value
     {
         private T _Value;
         
         get { return _Value; }
         set
         {
             if (_value != value)
                 _Value = value;             
         }
     }
}

Or simply use Equals instead of the == operator

public class Test<T>
{
     public T Value
     {
         private T _Value;
         
         get { return _Value; }
         set
         {
             if (!_value.Equals(value)
                 _Value = value;             
         }
     }
}
like image 114
gdoron is supporting Monica Avatar answered Oct 19 '22 06:10

gdoron is supporting Monica