2

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...

Bohemian
  • 412,405
  • 93
  • 575
  • 722
Grzegorz Sławecki
  • 1,727
  • 14
  • 27

1 Answers1

1

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.

Community
  • 1
  • 1
Grzegorz Sławecki
  • 1,727
  • 14
  • 27