code_junkie

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

Nov 10th, 2011
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. List<string> sl = new List<string>();List<object> ol;ol = sl;
  2.  
  3. List<string> sl = new List<string>();List<object> ol;ol = (List<object>)sl;
  4.  
  5. List<object> ol = new List<object>();List<string> sl;sl = (List<string>)ol;
  6.  
  7. List<string> sl = new List<string>();
  8. IEnumerable<object> ol;
  9. ol = sl.Cast<object>();
  10.  
  11. List<string> sl = new List<string>();
  12. // Add strings to sl
  13.  
  14. List<object> ol = new List<object>();
  15.  
  16. foreach(string s in sl)
  17. {
  18. ol.Add((object)s); // The cast is performed implicitly even if omitted
  19. }
  20.  
  21. var sl = new List<string>();
  22. // Add strings to sl
  23.  
  24. var ol = new List<object>(sl.Cast<object>());
  25.  
  26. // OR
  27. var ol = sl.Cast<object>().ToList();
  28.  
  29. // OR (note that the cast to object here is required)
  30. var ol = sl.Select(s => (object)s).ToList();
  31.  
  32. List<string> sl = new List<string>();//populate slList<object> ol = new List<object>(sl);
  33.  
  34. List<object> ol = new List<object>();ol.AddRange(sl);
  35.  
  36. List<string> sl = new List<string>();
  37. List<object> ol = sl.Cast<object>().ToList();
  38.  
  39. object[] a = new string[] {"spam", "eggs"};
  40.  
  41. public IList<B> ConvertIList<D, B>(IList<D> list) where D : B
  42. {
  43. List<B> newList = new List<B>();
  44.  
  45. foreach (D item in list)
  46. {
  47. newList.Add(item);
  48. }
  49.  
  50. return newList;
  51. }
  52.  
  53. private List<Leerling> Leerlingen = new List<Leerling>();
  54.  
  55. Leerlingen = (List<Leerling>)_DeserialiseerLeerlingen._TeSerialiserenObjecten.Cast<Leerling>();
Add Comment
Please, Sign In to add comment