There is no boxing conversion or type parameter conversion from 'TKey' to 'System.IEquatable'

Viewed 361

I have the following code

    public abstract class BaseEntity<TKey> : IIdentifiable<TKey>
    {
        public TKey Id { get; set; }
    }

    public interface IIdentifiable<TKey> where TKey : IEquatable<TKey>
    {
        TKey Id { get; set; }
    }

That generate this beautiful error message on BaseEntity

Error CS0314 The type 'TKey' cannot be used as type parameter 'TKey' in the generic type or method 'IIdentifiable'. There is no boxing conversion or type parameter conversion from 'TKey' to 'System.IEquatable'

What am I doing wrong?

1 Answers

As shown in the error message:

There is no boxing conversion or type parameter conversion from 'TKey' to 'System.IEquatable'

Specifying the constraint again in the abstract class level will solve the issue:

    public abstract class BaseEntity<TKey> : IIdentifiable<TKey> where TKey : IEquatable<TKey>
{
    public TKey Id { get; set; }
}

public interface IIdentifiable<TKey> where TKey : IEquatable<TKey>
{
    TKey Id { get; set; }
}

And that's because Tkey in the abstract class is different than the TKey in the interface so you should specify the constraint again to make it the same boxing type.

For example this code will be valid too:

public abstract class BaseEntity<TKey2> : IIdentifiable<TKey2> where TKey2 : IEquatable<TKey2>
{
    public TKey2 Id { get; set; }
}

public interface IIdentifiable<TKey> where TKey : IEquatable<TKey>
{
    TKey Id { get; set; }
}
Related