Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InvalidCastException when casting from base class to inherited class?

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.)

like image 802
Uchendu Nwachuku Avatar asked Mar 23 '26 08:03

Uchendu Nwachuku


2 Answers

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.

like image 186
jason Avatar answered Mar 25 '26 21:03

jason


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.

like image 45
StriplingWarrior Avatar answered Mar 25 '26 21:03

StriplingWarrior



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!