2

I have an interface:

interface IKey<TId, TName>
    where TId: IEquatable<TId>
    where TName: IEquatable<TName>
{
    TId Id { get; set; }
    TName Name { get; set; }
}

Then I implement IKey like this:

class Item : IKey<int, string>
{
    int Id { get; set; }
    string Name { get; set; }
    //...
}

And I have collection that should work with these items

class ItemCollection<T>
    where T : IKey<TId, TName> //Any type that implements IEquatable<...>
    where TId: IEquatable<TId>
    where TName: IEquatable<TName>
{
    //...
}

And the problem is that it doesn't work. Is there a way I can do this correctly?

There is another implementation whithout IEquatable, using IKey<out TId, out TName> and IKey<object, object> but it doesn't work with value-types and uses Object.Equals.

1 Answer 1

6

The problem is your attempting to use TId and TName in ItemCollection without ever defining them. Because they are part of the interface constraint on T they need to either be concrete types are specified as type parameters.

class ItemCollection<T, TId, TName>
    where T : IKey<TId, TName>
    where TId : IEquatable<TId>
    where TName : IEquatable<TName>
{
    //...
}

Example using hard coded types

class ItemCollection<T>
    where T : IKey<string, string>
{
    //...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.