I have to be missing something obvious here. I don’t get why this cast of the results of a linq query returns null and not the typed list I’m requesting.
IList<IMyDataInterface> list = query.ToList() as IList<IMyDataInterface>;
The complete code to run this is below. This is a knowledge gap I need to bridge. I have tried all kinds of permutations of casts to get it to work. I get no Exceptions, just a null. Of note is that the Linq query is selecting its results into instances of my custom ‘MyDataClass’ which implements IMyDataInterface
class Program { static void Main(string[] args) { IMyFunctionalInterface myObject = new MyClass(); //myObject.Get() returns null for some reason... IList<IMyDataInterface> list = myObject.Get(); Debug.Assert(list != null, 'Cast List is null'); } } public interface IMyFunctionalInterface { IList<IMyDataInterface> Get(); } public class MyClass : IMyFunctionalInterface { public IList<IMyDataInterface> Get() { string[] names = { 'Tom', 'Dick', 'Harry', 'Mary', 'Jay' }; var query = from n in names where n.Contains('a') select new MyDataClass { Name = n.ToString() }; //There IS data in the query result Debug.Assert(query != null, 'result is null'); //but the cast here makes it return null IList<IMyDataInterface> list = query.ToList() as IList<IMyDataInterface>; return list; } } public interface IMyDataInterface { string Name { get; set; } } public class MyDataClass : IMyDataInterface { public string Name { get; set; } }
The problem here is one of covariance.
First, your example is a bit too complicated. I have removed some fluff. Also, I’ve added some diagnostics that illuminate the problem.
The output of this program is:
Note that we’re trying to cast a
List<C>toList<I>which doesn’t work in C# 3.0.In C# 4.0 you should be able to do this, thanks to the new co- and contra-variance of type parameters on generic interfaces.
Also, your original question asked about
IQueryablebut that’s not relevant here: the query expression you supplied creates anIEnumerable<string>not anIQueryable<string>.EDIT: I want to point out that your ‘cast’ using the
asoperator is technically not a cast, but is a ‘type conversion’. If you had use a cast, you would have gotten an exception with useful information. If I change to:I get an
InvalidCastExceptionwith: