Generic constraint type for ValueType in C #

I have a generic class that constrains the arguments to use types int

or long

. My problem is that I need to compare variables of this type of arguments in my method. But the compiler said that I cannot compare these points -

Operator '==' cannot be applied to operands of type "K" and "K"

My code:

public class MyClass<T,K>
    where T : Entity<K>
    //where K : ??? - what can I do?
{
    public virtual bool MyMethod(T entity1, T entity2)
    {
        return entity1.EntityId == entity2.EntityId;//Operator '==' cannot be applied to operands of type 'K' and 'K'
    }
}
public abstract class Entity<T>
{
    public T EntityId{get;set;}
}

      

+3


source to share


2 answers


You can limit K

on IEquatable<K>

and use Equals

:



public class MyClass<T,K>
    where T : Entity<K>
    where K : IEquatable<K>
{
    public virtual bool MyMethod(T entity1, T entity2)
    {
        return entity1.EntityId.Equals(entity2.EntityId);
    }
}

      

+4


source


Instead of using an operator, ==

you can always use a static method object.Equals(object, object)

.

This object will refer to a method - possibly overridden - Equals

of what is passed to it, which for value types must be implemented to support equality of value.

So, your method can be written like this:



public virtual bool MyMethod(T entity1, T entity2)
{
    return object.Equals(entity1.EntityId, entity2.EntityId);
}

      

You don't need an additional constraint, and in fact it would still work if it T

was a reference type.

+7


source







All Articles