I have a class QuoteAddress which inherits from Address, and a generic collection called AddressCollection which holds these address objects.
When I try to cast a QuoteAddress to Address, everything works fine. But when I try to cast AddressCollection<QuoteAddress> to AddressCollection<Address> I get a compile-time error:
Cannot implicitly cast type AddressCollection<QuoteAddress> to AddressCollection<Address>.
EDIT: I don't believe this question is a duplicate because the suggested duplicate question assumes the collection is ReadOnly. I need to be able to Add/Remove items from my collection.
What can I do to work around this? Since one inherits from the other, I thought this would be a straightforward cast.
public class QuoteAddress : Address
{
...
}
I also have an AddressCollection class which holds these addresses.
public class AddressCollection<T> : AddressHack where T : Address, new()
{
...
}
I have two client objects that each have a property called Addresses which hold addresses. Client1's Address proprety is of type AddressCollection<QuoteAddress>, while Client2's is of type AddressCollection<Address>.
Client1
public class Client1
{
...
public AddressCollection<QuoteAddress> Addresses { get; set; }
...
}
Client2
public class Client2
{
...
public AddressCollection<Address> Addresses { get; set; }
...
}
Lastly, I have an AddressControl class with a properties called CurrentAddressCollection of type AddressCollection<Address> and CurrentAddress of type Address.
public class AddressControl : System.Web.UI.UserControl
{
public Address CurrentAddress { get; set; }
public AddressCollection<Address> CurrentAddressCollection { get; set; }
}
Client1 c1 = new Client1();
AddressControl.CurrentAddress = c1.Addresses.GetFirstAddress(); // GetFirstAddress returns type of QuoteAddress
AddressControl.CurrentAddressCollection = c1.Addresses; // compile-time error
Client2 c2 = new Client2 ();
AddressControl.CurrentAddress = c2.Addresses.GetFirstAddress(); // GetFirstAddress returns type of Address
AddressControl.CurrentAddressCollection = c2.Addresses; // no problems