Julian Easterling
Julian Easterling

Reputation: 840

How can I perform this simple equality comparison?

I have the following code:

public abstract class RepositoryBase<T, TId> : IRepository<T, TId>
    where T : class, IEntityWithTypedId<TId>
    where TId : IEquatable<TId>, IComparable<TId>
{
    public T FindById(TId id)
    {
        T entity;

        using (this.Context) // This simply returns the NHibernate Session
        {
            var entities = from e in this.Context.Get()
                           // where e.Id.Equals(id)
                           where e.Id == id
                           select e;

            entity = entities.FirstOrDefault();
        }

        return entity;
    }
}

If I use the where e.Id == id clause, I get the error:

error CS0019: Operator '==' cannot be applied to operands of type 'TId' and 'TId'

error even though I've told the compiler that TId must implement IEquatable and IComparable

If I use the where e.Id.Equals(id) clause, the code will compile, but I get a NotSupported Exception from NHibernate when it executes the query on the FirstOrDefault line.

I know that I must be missing something in the design however the solution has eluded me for several days.

Upvotes: 0

Views: 157

Answers (1)

Adam Robinson
Adam Robinson

Reputation: 185643

While it might seem intuitive, operators (==, <, >, etc.) have nothing to do with interfaces like IComparable, IEquatable, etc. Unfortunately, operators can't be applied to generic types.

Unlike functions like Equals, operators are static and therefore not polymorphic. Since it's not possible to access static members of generic types, operators are inaccessible.

Upvotes: 1

Related Questions