public abstract class ContentManagedEntity
{
public Guid Guid { get; set; }
public bool Active;
public int DisplayOrder;
}
public class StoreCategory : ContentManagedEntity
{
public string Name { get; set; }
}
public class XMLStoreCategory : StoreCategory, IXMLDataEntity
{
public bool Dirty = false;
}
void main() {
var storecategory = new StoreCategory { Name = "Discount Stores" };
var xmlstorecategory = (XMLStoreCategory) storecategory; // Throws InvalidCastException
}
Is there a reason it throws an InvalidCastException at runtime on the last line?
(Bah, as I wrote this, the answer popped into my head, clear as day. Posting it up for posterity, and just to make sure I have it right.)
You're asking this:
class Animal { }
class Cat : Animal { }
class ShortHairedCat : Cat { }
ShortHairedCat shortHairedCat = (ShortHairedCat)new Cat();
Is a Cat a ShortHairedCat? Not necessarily. In this particular case, new Cat() is a Cat that is not a ShortHairedCut so of course you get a runtime exception.
Remember, inheritance models is a relationships. It is not necessarily the case that a Base is a Derived, so in general, "downcasting" is dangerous.
All XMLStoreCategory objects are StoreCategorys, but not all StoreCategorys are XMLStoreCategorys. In this case you're creating a StoreCategory and trying to cast it into something it's not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With