I'm getting a compiation error that I don't understand. I am convinced that this code should work but it is not compiling. Am I just forgetting something obvious? This is my code and the error message:
using System.Collections.Generic;
using System.Linq;
public class A { }
public class B : A { }
public class C : A { }
public static class Foo
{
public static List<A> All = new List<A>
{
new A(),
new B(),
new C()
};
public static List<B> Bs()
{
/*
The error is given here:
(field) static List<A> Foo.All
'List<A>' does not contain a definition for 'ToList' and
the best extension method overload 'Enumerable.ToList<B>(IEnumerable<B>)'
requires a receiver of type 'IEnumerable<B>'
*/
return All.ToList<B>();
}
}
I have Googled and people say I should make sure to import System.Linq but, as you can see, I've already done that, and I'm still having this problem. What am I missing? If relevant, this error is seen while using Unity 20121.2.7f1 and VSCode.
CodePudding user response:
You are forcing it to convert to a B which not all As are Bs. List<A> doesn't implement IEnumerable<B> which thats what ToList<T> requires.
Perhaps you would want something like All.OfType<B>().ToList()?
