2

Possible Duplicate:
In C#, why can't a List<string> object be stored in a List<object> variable

I thought this could work:

private List<DateTime> _dateTimes = new List<DateTime>();
private List<String> _strings = new List<String>();

private List<List<Object>> _listOfLists = new List<List<Object>>();

_listOfLists.Add(_dateTimes);
_listOfLists.Add(_strings);

But, I get a compiler error stating that the .Add method has some invalid arguments...Does anybody see why? And, what can be a solution to have a generic List of Lists?

Community
  • 1
  • 1
Youp Bernoulli
  • 5,303
  • 5
  • 39
  • 59

2 Answers2

5

The problem is that for reasons related to type safety, you cannot treat a List<string> as a List<object>. If you could, this would be possible:

var list = (List<object>)(new List<string>());
list.Add((object)42); // this should never be allowed to compile

What you can do is this:

private List<DateTime> _dateTimes = new List<DateTime>();
private List<String> _strings = new List<String>();

private List<IList> _listOfLists = new List<IList>();

_listOfLists.Add(_dateTimes);
_listOfLists.Add(_strings);

This works because List<T> implements IList. Of course, you have now "forced" the compilation of the code by forfeiting compile-time type safety. In essence you accept that if you do try to add an object of incorrect type to one of the IList instances you will get a runtime exception.

Jon
  • 428,835
  • 81
  • 738
  • 806
0

A List<string> is no List<object>. If that were the case you could cast a List<string> to a List<object> at runtime and then call the Add method with a type other than string. This would corrupt the state of the list.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262