How to solve Operator '!=' cannot be applied to operands of type 'T' and 'T' [duplicate]
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;
}
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;
}
}
}
T
can be any type. You cannot use ==
/!=
on structs, unless such operators are defined on the (struct) type.