I have those classes, an implementation of active record pattern:
public abstract class RecordCollection<T> : ObservableCollection<T> where T : Record
public abstract class Record : INotifyPropertyChanged
every time i want to define a row of a database (ie a Contact), I create a new record class, like:
public class Contact : Record
and a collection of row of database (ie Contacts) as:
public class ContactCollection : RecordCollection<Contact>
but after that i can’t use generic for contain a record colletcion:
ContactCollection contColl = new ContactCollection(databaseman dbMan);
contColl.Load();
RecordCollection<Record> recordColl = contColl;
it give me “Cannot implicitly convert type ContactCollection to >”. Any help would be appreciated.
This casting is not permitted simply because this could happen:
Now we could do:
This is what is called covariance and contravariance (read more here) between generic types. For this to work,
contCollmust implement a “out” only interface, which it doesn’t. By this I mean that for type safety to be preserved,contCollcan not allow to add items (more formally,Tcan only be the return type of a method)Note that in arrays this is allowed, but its a broken covariance, which is unfortunate: more here