I’m a bit stumped about how to perform the necessary cast in the following:
public IList<IMyClass> Foo()
{
IList<IMyClass> foo = SomeQuery();
var result = foo.GroupBy(x => x.bar).Select(x => new MyClass()).ToList();
// So now I have a List<MyClass> which needs casting as IList<IMyClass>
return result;
}
using an explicit cast fails at run time. The error message isn’t helpful but I’m guessing it maybe something to do with the GroupBy as I wouldn’t normally expect to have any problem with something like this.
It’s nothing to do with
GroupBy– it’s becauseIList<T>is invariant. If you could cast aList<MyClass>toIList<IMyClass>then the caller could then add an instance of a type which implementedIMyClassbut wasn’t aMyClass. (I usually think of this in terms of real world objects: a bunch of bananas isn’t a fruit bowl: you can add an apple to a fruit bowl, but not to a bunch of bananas.)The simplest way would be to manually specify the type in the Select clause:
This means
resultwill actually be aList<IMyClass>. I don’t know the type of item withinfoowhich makes it tricky to give it in more detail – given your comment, I’ll assume that that’sIMyClass, and that x.bar is of typeBar.Another alternative (which would be more useful if you wanted to use a query expression for the group/select part) would be to use
Cast:Or perform the cast within the Select lambda expression itself:
EDIT: Apologies for the
Selectfailure. It’s somewhat annoying that you have to specify both the source and the result, but there’s no easy way of fixing that 🙁 Given the ugliness involved, you may well be best off withCast.