InvalidCastException: Unable To Cast Objects of type [base] to type [subclass]

You’ve got it in reverse: A cast from an object of a base class to a subclass will always fail, because the base class has only the properties of the the base class (not the subclass).

Since, as you say, the subclass has all the properties of the base class (it “is-a” base-class object), then a cast from the subclass to the base class will always succeed, but never the reverse.

In other words, you can think of all leopards as cats, but you cannot take an arbitrary cat and treat it like a leopard (unless it’s already a leopard to begin with).

You need to either return a CustomMembershipUser object instead of a MembershipUser object, or define another explicit cast separate function which converts MembershipUsers to CustomMembershipUsers by making a new CustomMembershipUser object. You cannot get a CustomMembershipUser object out of nowhere; it has be created first, either directly or by instantiating a subclass of CustomMembershipUser (not a base-class).

Edit:

I was wrong about defining an explicit cast to the subclass. This is not possible (as the error you see indicates). You now seem to be in the exact same situation as the asker of this question. Casting is not really the way to go here — either create CustomMembershipUser objects to begin with (which are usable directly as MembershipUser objects), or write a conversion method which accepts a MembershipUser and creates a CustomMembershipUser.

The only time it makes sense to cast from a base object to a subclass object is when it is already a subclass object (but the variable holding it is of the base class type).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)