Reputation: 1797
I got the following code and it gives me compile error:
cannot convert from 'UserQuery.SomeClass<int>' to UserQuery.Interface<System.IConvertible>'
the code:
void Main()
{
List<Interface<IConvertible>> values = new List<Interface<IConvertible>>();
values.Add(new SomeClass<int>() {Value = 50 });
}
interface Interface<out T> where T : IConvertible
{
T Value { get; }
}
class SomeClass<T> : Interface<T> where T : IConvertible
{
public T Value { get; set; }
}
However, trying to add SomeClass<string>
works fine.
values.Add(new SomeClass<string>() {Value = "50" });
Could anyone please explain me why I can do it for string, but not for int nor double and so on...
Upvotes: 2
Views: 195
Reputation: 1797
I've found the answer here: Is this a covariance bug in C# 4?
Generally, variance is not supported for value types. That's why it won't work for int, but does work for string.
Upvotes: 1