Uchendu Nwachuku
Uchendu Nwachuku

Reputation: 450

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

Upvotes: 2

Views: 2450

Answers (3)

Adam Lear
Adam Lear

Reputation: 38778

You instantiated the object as StoreCategory. It's not the same as XMLStoreCategory, so you can't cast it that way.

The case where the cast would work is something like this:

StoreCategory storecategory = new XMLStoreCategory { Name = "Discount Stores" };
var xmlstorecategory = (XMLStoreCategory) storecategory;

That will work, but in your particular case is somewhat useless. Just instantiate XMLStoreCategory and you'll be good to go.

Upvotes: 2

jason
jason

Reputation: 241691

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.

Upvotes: 4

StriplingWarrior
StriplingWarrior

Reputation: 156574

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.

Upvotes: 3

Related Questions