I am completely confused by now. I want to create generic class with method that is able to correctly compare if provided entity is different than previous one. Like this pseudocode:
public void SetPropertyIfDifferent(T value)
{
if (this.classProperty != value)
{
this.classProperty = value;
// And I want to do something additional here [...]
}
}
By different, I mean that when T is reference type it will compare reference, so:
Example Reference Types
-
somePocoObject1 == somePocoObject2 // Different
-
someCollider == null // Different
-
someTransform1 == someTransform2 // Different
-
someTransform1 == null // Different
-
someTransform1 == someTransform1 // The same
and when T is value type it will correctly compare too:
Example Value Types
-
Vector3(0,0,1) == Vector3(0,0,1) // The same
-
Vector3(1,1,1) == Vector3(0,0,1) // Different
-
1.0 == 3.0 // Different
-
87 = 87 // The same
The problem is, I am unable to make it work without boxing.
In generic class â==â operator cannot be used, so I would need to use Equals or
EqualityComparer, but it seems it does not work. I am aware of special overload for == in unity and still I am confused how things work. See following example:
Code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ComparerTest : ComparerTestBase<GameObject>
{
IEnumerator Start()
{
Debug.LogWarning(obj == null);
Debug.LogWarning(Object.Equals(obj, null));
Debug.LogWarning(EqualityComparer<GameObject>.Default.Equals(obj, null));
this.Test(obj);
yield return new WaitForSeconds(1f);
}
}
public abstract class ComparerTestBase<T> : MonoBehaviour
{
public T obj = default(T);
public void Test(T value)
{
Debug.Log(value == null);
Debug.Log(Object.Equals(value, null));
Debug.Log(EqualityComparer<T>.Default.Equals(value, default(T)));
}
}
When the obj is not set (none), the output is:
True
False
False
False
False
False
Why only first comparison works?
Why it says it is not null while it is null (or empty or whatever)?
What should I do?