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

C#Generics

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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;
}

Solution 2 - C#

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;             
         }
     }
}

Solution 3 - C#

T can be any type. You cannot use ==/!= on structs, unless such operators are defined on the (struct) type.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDarfView Question on Stackoverflow
Solution 1 - C#user541686View Answer on Stackoverflow
Solution 2 - C#gdoron is supporting MonicaView Answer on Stackoverflow
Solution 3 - C#leppieView Answer on Stackoverflow