I have two classes defined like
public class PostleitzahlList : ObservableCollection<Postleitzahl> {
}
public class Postleitzahl : IPostleitzahl {
}
Now I have a Service-Class which contains
PostleitzahlList _postleitzahlList;
This Serviceclass has also to implement a Property of a Service-Interface which returns _postleitzahlList – but this Interface only knows IPostleitzahl – it doesn’t know PostleitzahlList or Postleitzahl. this Property should be used for Binding in WPF.
I am trying now to declare and implement this Property. I have tried
public ObservableCollection<IPostleitzahl> PostleitzahlList {
get { return this._postleitzahlList; }
}
and
public IList<IPostleitzahl> PostleitzahlList {
get { return this._postleitzahlList; }
}
But both does not work.
The fallowing seems to work:
public IEnumerable<IPostleitzahl> PostleitzahlList {
get { return this._postleitzahlList; }
}
I ask me now
1. why does the first and second try not working?
2. what is the best solution to solve this?
The problem is with covariance. An
ObservableCollection<Postleitzahl>isn’t anObservableCollection<IPostleitzahl>, and ditto with lists. Here’s an example of why not:… but as you can see, you’re now trying to fetch a non-string reference and store it in a string variable. The only viable outcome would be an execution-time failure… and half the point of generics is to push error detection to compile-time.
Now
IEnumerable<T>is covariant inTbecause you can’t add any items via it – that makes it safe to apply that sort of conversion:For more information, read up on covariance and contravariance in generics in MSDN.
Do you need the
IPostleitzahlinterface? If you just exposed the properties viaObservableCollection<Postleitzahl>orIList<Postleitzahl>it would be fine. Alternatively, you could change your variable to be anObservableCollection<IPostleitzahl>and just happen to populate it by creatingPostleitzahlinstances.