RredCat
RredCat

Reputation: 5421

Generic type constrain for ValueType in C#

I have generic class that restricts arguments to use int or long types. My issue that I need to compare variables of this argument type in my method. But compiler said that I can't compare these items -

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

Upvotes: 3

Views: 90

Answers (2)

O. R. Mapper
O. R. Mapper

Reputation: 20731

Instead of using the == operator, you can always use the static object.Equals(object, object) method.

That object will invoke the - possibly overridden - Equals method of whatever is passed to it, which, for value types, should be implemented to support value equality.

So, your method could be written like this:

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

You wouldn't need an extra constraint, and in fact, it would even still work in some way if T were a reference type.

Upvotes: 7

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

You can constraint 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);
    }
}

Upvotes: 4

Related Questions