I have a bas class called Media
with two classes that inherit from it, Photo
and Video
. I am trying to create a collection for the media base class to hold those photo and video objects. So I have created a MediaList
class as follows:
public class MediaList: ICollection<Media>
{
private readonly XElement _mediaElement;
public MediaList(XElement mediaElement)
{
_mediaElement = mediaElement;
}
public IEnumerator<Media> GetEnumerator()
{
foreach (XElement element in _mediaElement.Elements())
{
Media media;
switch (element.Name.LocalName)
{
case "video":
media = new Video(element);
break;
case "photo":
media = new Photo(element);
break;
default:
media = null;
break;
}
yield return media;
}
}
//Rest of ICollection Implementation
}
When I iterate the list I get the following exception:
The value "Tool.Photo" is not of type "Tool.Video" and cannot be used in this generic collection.
If I am returning a Media
object, why is it throwing the exception? Is there a better way to get around this?