C
C#4mo ago
axa88

Help with parameter usage

I have the following classes defined (code redacted for brevity) Using .NET8 c#12 public interface ICollectionItem {} Which in turn is inherited by: public class CollectionItem : NotifyPropertyChanged, ICollectionItem {} And in turn is inherited by: public class DeviceItem : CollectionItem, IDisposable, IAsyncDisposable { public DeviceItem(DeviceCollectionBase<ICollectionItem> deviceCollection) {} } Which has a constructor so i can then create a DeviceItem instance from within yet another class: public abstract class DeviceCollectionBase<T> : PacedItemCollection<T>, IDisposable, IAsyncDisposable where T : ICollectionItem { protected override async Task UpdateCollection() { var v = new DeviceItem(this)... } } But the parameter this is flagged with the error CS1503 "Argument type DeviceCollectionBase<T>, is not assignable to parameter type DeviceCollectionBase<ICollectionItem>" , yet T is constrained to be an ICollectionItem! My covariance and/or contravariance games are shite, so i dont quite see where im going wrong, any help?
1 Reply
Omnissiah
Omnissiah4mo ago
if i remember correctly the reaons you can't it's that you could pass to that a more derived class DeviceCollectionBase<DerivedType1> which could have implementations that use specific DerivedType1 stuff to other DeviceCollectionBase<...> that can't use those specific implementations (you have to remember that DeviceCollectionBase<DerivedType1> is DerivedType1, or rather every implemented DeviceCollectionBase<> is a different type) honestly this inheritance stuff sometimes is so convoluted that i avoid it (EDIT no in fact the issue would be another i think: when you are using generic T in a derived class of DeviceCollectionBase you could be "fixing" that type to a more derived one; the types in DeviceCollectionBase<ICollectionItem> are not necessarily that specific T, so a DeviceCollectionBase<ICollectionItem> of Device1 items vs a Device2CollectionBase:DeviceCollectionBase<Device2>)
Want results from more Discord servers?
Add your server