Why doesn't allow covariation here? #3985
-
I find an interesting thing and I'm confused whether it's due to limit of compiler or is just by design. Codes see below, public class SingleHashFunctionList<T> : IHashFunctionList
where T : IHashFunction //Notice this 'where'
{
private readonly IReadOnlyList<T> _hashFunctions;
public SingleHashFunctionList()
{
// Skip init work of '_hashFunctions'
HashFunctions = _hashFunctions; //Compiler error: ...cannot implictly convert...
}
public IReadOnlyList<IHashFunction> HashFunctions { get; }
} Since the interface |
Beta Was this translation helpful? Give feedback.
Answered by
YairHalberstadt
Oct 8, 2020
Replies: 1 comment 2 replies
-
You need to add the class constraint, since covariant type parameters don't work with structs: public class SingleHashFunctionList<T> : IHashFunctionList
where T : class, IHashFunction
{
private readonly IReadOnlyList<T> _hashFunctions;
public SingleHashFunctionList()
{
// Skip init work of '_hashFunctions'
HashFunctions = _hashFunctions;
}
public IReadOnlyList<IHashFunction> HashFunctions { get; }
} |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
LeaFrock
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You need to add the class constraint, since covariant type parameters don't work with structs: