For brevity, I will be generic here. I have a base class – Review – that has a child – ShelfAwarenessReview.
I also have a method, whose signature is required by an interface:
public List<Review> GetReviews(string filePath)
{
XElement xmlDoc = XElement.Load(filePath);
var dtos = from item in xmlDoc.Descendants("message")
select new ShelfAwarenessReview()
{
PubDate = item.Element("meta").Attribute("permlinkdate").Value,
Summary = item.Element("meta").Element("summary").Value,
Isbn = item.Element("BookInfo").Element("ISBN").Value
};
List<Review> reviews = new List<Review>();
reviews = dtos.ToList();
return reviews;
}
Now, the error I am getting is that List<ShelfAwarenessReview> cannot be cast implicitly to List<Review>.
I have tried several types of casting – or, at least I thought I did – and it doesn’t work. I thought because ShelfAwarenessReview is a child of Review that this would work. After all, as the inheritance adage goes, “All toasters are appliances but not all appliances are toasters”…
What do I need to do to get a list of ShelfAwarenessReviews to exit the method in as a list of its parent type (Review)?
Just an FYI, the code calling this method is intended not to care about the types reviews it is getting. The subsequent code will operate on whatever.
I appreciate it big time.
Well to start with, you don’t need to create an empty
List<Review>which you then ignore 🙂Here’s the simplest solution:
If you’re using .NET 4 and C# 4, there’s another alternative due to generic covariance which works for
IEnumerable<T>but notList<T>:Note the explicit specification of the type of
dtos. The query expression will be of typeIEnumerable<ShelfAwarenessReview>but that’s implicitly convertible (in C# 4) toIEnumerable<Review>.