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?
03 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; } 8T 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; } } } 3T can be any type. You cannot use ==/!= on structs, unless such operators are defined on the (struct) type.