code_junkie

Linq - Casting IQueryable to IList returns null - WHY

Nov 13th, 2011
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. IList<IMyDataInterface> list = query.ToList() as IList<IMyDataInterface>;
  2.  
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. IMyFunctionalInterface myObject = new MyClass();
  8.  
  9.  
  10. //myObject.Get() returns null for some reason...
  11. IList<IMyDataInterface> list = myObject.Get();
  12.  
  13. Debug.Assert(list != null, "Cast List is null");
  14. }
  15. }
  16.  
  17. public interface IMyFunctionalInterface
  18. {
  19. IList<IMyDataInterface> Get();
  20. }
  21.  
  22. public class MyClass : IMyFunctionalInterface
  23. {
  24. public IList<IMyDataInterface> Get()
  25. {
  26. string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };
  27.  
  28. var query = from n in names
  29. where n.Contains("a")
  30. select new MyDataClass
  31. {
  32. Name = n.ToString()
  33. };
  34.  
  35. //There IS data in the query result
  36. Debug.Assert(query != null, "result is null");
  37. //but the cast here makes it return null
  38. IList<IMyDataInterface> list = query.ToList() as IList<IMyDataInterface>;
  39.  
  40. return list;
  41. }
  42.  
  43. }
  44. public interface IMyDataInterface
  45. {
  46. string Name { get; set; }
  47. }
  48.  
  49. public class MyDataClass : IMyDataInterface
  50. {
  51. public string Name { get; set; }
  52. }
  53.  
  54. class Program
  55. {
  56. static void Main(string[] args)
  57. {
  58. var names = new[] { "Tom", "Dick", "Harry", "Mary", "Jay" };
  59.  
  60. var query = from n in names
  61. select new C
  62. {
  63. S = n
  64. };
  65.  
  66. //There IS data in the query result
  67. Debug.Assert(query != null, "result is null");
  68.  
  69. //but the conversion here makes it return null
  70. var list = query.ToList() as IList<I>;
  71. Console.WriteLine(query.ToList().GetType());
  72.  
  73. // this assert fires.
  74. Debug.Assert(list != null, "Cast List is null");
  75. }
  76. }
  77.  
  78. interface I
  79. {
  80. string S { get; set; }
  81. }
  82.  
  83. class C : I
  84. {
  85. public string S { get; set; }
  86. }
  87.  
  88. var list = (IList<I>)query.ToList();
  89.  
  90. var query = from n in names
  91. where n.Contains("a")
  92. select new MyDataClass
  93. {
  94. Name = n.ToString()
  95. } as IMyDataInterface;
  96.  
  97. IList<IMyDataInterface> list = query.ToList() as IList<IMyDataInterface>;
  98.  
  99. List<MyDataClass> tmp = query.ToList();
  100. IList<IMyDataInterface> list = tmp as IList<IMyDataInterface>;
  101.  
  102. IList<IMyDataInterface> list = query.ToList().Cast<IMyDataInterface>();
Add Comment
Please, Sign In to add comment