3

Basically I want to be able to do the following but I think I've designed my class hierarchy wrong or I'm missing something crucial related to polymorphism/generic collections:

ISearchableMediaList<IMedia> list = new MovieList();

The above line produces the following error: Cannot implicitly convert type 'MovieList' to 'ISearchableMediaList<IMedia>'. An explicit conversion exists (are you missing a cast?). Shouldn't I be able to substitute the derived type for the interface without casting? (see the class diagram at the bottom for more details).


public interface IMedia 
{
    string Title { get; set; }
    double Rating { get; set; }
    DateTime Date { get; set; }
    string Comments { get; set; }
}

public class Media : IMedia { ... }
public class Movie : Media { // Adds on movie-specific properties }
public class Book : Media { // Adds on book-specific properties }

public interface IMediaList<T> : ISearchableMediaList<T> where T : IMedia
{ ... }

public interface ISearchableMediaList<T> : IList<T> where T : IMedia
{
    IList<string> SearchCategories { get; }
    IList<T> Search(string query, string category);
}

public class MediaList<T> : BindingList<T>, IMediaList<T> where T : IMedia
{ 
    // Implements common search functionality and other stuff 
}
public class MovieList : MediaList<Movie> 
{ 
    // Implements movie-specific searching and other stuff
}
public class BookList : MediaList<Book> 
{ 
    // Implements book-specific searching and other stuff
}

enter image description here

Brett
  • 436
  • 3
  • 18

1 Answers1

1

You cannot use ISearchableList<IMedia>, you must use the appropriate implemented type like so:

      ISearchableMediaList<Movie> list = new MovieList();
Pieter Geerkens
  • 11,775
  • 2
  • 32
  • 52
  • Yes, this is what I need to do but I was hoping I would just be able to do `ISearchableMediaList list = new MovieList();` so I wouldn't have to make the consuming class (a view model) generic as well. Is it because generic covariance? – Brett Jul 07 '13 at 19:45
  • Try using `` and `` and see if one works. – Pieter Geerkens Jul 08 '13 at 02:49