I have the following class hierarchy:
public abstract class BaseData { //some properties } public class CoData : BaseData { //some properties }
I am working with a method that requires the return type to be List<BaseData>. In the method, I have access to List<CoData>
public List<BaseData> Save() { List<CoData> listCoData = GetData(); return listCoData; }
If I understand correctly, I can upcast from a CoData to a BaseData. But, when I have a list, it errors out even if I explicitly try to typecast.
Error:
Error 118 Cannot implicitly convert type 'System.Collections.Generic.List<CoData>' to System.Collections.Generic.List<BaseData>'
EDIT:
mquander’s Conversion approach seems to work for me in 3.0
Is downcasting done the same way as well? from
ie., Can I do this – List<CoData> listCoData = listBaseData.Cast<BaseData>().ToList();
Yes; welcome to variance. Ultimately, it isn’t a list of
BaseData– for example, if you had another subclass, aList<BaseData>would (at compile time) let you.Addit… but the runtime type wouldn’t let you. The compiler is stopping you making a mistake.In some scenarios, generics can help here… I discuss this at the end of this blog entry. Note that .NET 4.0 variance doesn’t apply to lists.