2

I get the compiler error when trying to compare generic enums. All looks fine and I don't know what's wrong.

Error message: Operator == cannot be applied to operands of type T and T

public class SpriteLink<T> 
{
    public T id;
    public Sprite sprite;

    public SpriteLink(T id, Sprite sprite)
    {
        this.id = id;
        this.sprite = sprite;
    }
}

public class LinkList<T>
{
    public List<SpriteLink<T>> links = new List<SpriteLink<T>>();

    public bool Contains(T id)
    {
        links[0].id = id; // compiler passes this line without any errors
        return links.Any(link => link.id == id); // but throws compiler error here (why?)
    }

    public bool Set(T id, Sprite sprite)
    {
        if (!Contains(id))
        {
            links.Add(new SpriteLink<T>(id, sprite));
            return true;
        }
        return false;
    }
}

public LinkList<SurfaceID> surfaceLinks = new LinkList<SurfaceID>();
public LinkList<FloorID> floorLinks = new LinkList<FloorID>();

SurfaceID and FloorID are just enums with some fields.

Ka Res
  • 311
  • 2
  • 3
  • 17
lancaster
  • 134
  • 9
  • T can be any type. You can use Equals instead – Anatoli Klamer Jan 24 '18 at 15:33
  • 1
    Similar question https://stackoverflow.com/questions/8982645/how-to-solve-operator-cannot-be-applied-to-operands-of-type-t-and-t – Anatoli Klamer Jan 24 '18 at 15:33
  • or define that T can only be a `class`, then you can use `==` – Michael Jan 24 '18 at 15:34
  • There must be a lot of duplicates to this question... The problem is that there is no generic way for the compiler to emit code for `==`. It works for reference types (if you put a constraint `where T : class`), but that would do _only a reference comparison_. It's not possible at all for value types. – René Vogt Jan 24 '18 at 15:35
  • Can you change links to dictionary and `return links.Any(link => link.id == id);` to `links[id]` – Anatoli Klamer Jan 24 '18 at 15:38
  • 1
    Thank you all, comparison by `links.Any(link => EqualityComparer.Default.Equals(link.id, id))` works for me. – lancaster Jan 24 '18 at 15:48

0 Answers0