1

When I write this code it allow me

IEnumerable<object> creator = new List<string>();

But when I write

IEnumerable<object> creator = new List<int>();

it shows compile time error:

Error CS0266 Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)

I don't know why it is happening.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Pankaj Moriya
  • 195
  • 1
  • 12

2 Answers2

5

That's because value types do not support co-/contravariance.

string is a reference type, so it works fine. int is a value type, so it doesn't.

You may, however, explicitly convert your list to a list of boxed ints:

IEnumerable<object> creator = listOfInts.Select(i => (object)i);

EDIT:

Contrary to many other answers, value types do in fact inherit from object. It's also mentioned in the struct usage guide. That is not the reason for value types being invariant!

V0ldek
  • 9,623
  • 1
  • 26
  • 57
-1

I believe this is because int is a value type. although int ultimately does inherit from object, int can not be inherited from ; you can compare their base types with this:

Console.WriteLine(10.GetType().BaseType.Name);
        Console.WriteLine("".GetType().BaseType.Name);
Jamiec
  • 133,658
  • 13
  • 134
  • 193
Stucky
  • 156
  • 7
  • yes, and i did point this out. however you can not inherit FROM int. "A struct cannot inherit from another struct or class, and it cannot be the base of a class." – Stucky Jul 05 '19 at 08:38