Given the following classes:
public class ContentItem : IEquatable<ContentItem>
{
...
}
and
public class Widget : ContentItem, IWidget
{
...
}
why I can’t do this:
List<Widget> widgets = _repository.GetItems(widgetType);
where
_repository.GetItems(widgetType) returns IEnumerable<ContentItem>?
Essentially I already have a repository implementation which works on ContentItem class and I would like to use that same repository also for working with Widget class basically because Widget has the same base properties and only introduces few new ones that just hold some information (they come from IWidget interface) and don’t have any impact on how repository should handle the class). I don’t want to make another repository class just to replace all occurences of ContentItem with Widget.
Should I make my changes by explicitly specifing casts or changing my repository (or repository interface, which I also have)? If possible, I would like to avoid various constructs such as AsEnumerable(), ToList() or explicit casts.
Because a
ContentItemis not aWidget– it’s the other way round. Even then anIEnumerable<ContentItem>is different from aList<Widget>, you can achieve what you want by doing something like this:But this will only work if you are really returning an enumeration where each
ContentItemis really aWidget.