user204588
user204588

Reputation: 1633

Trouble with explicit casting

I have a product class in C# that inherits from another product class

using ExternalAssemb.ProductA;

public class MyProduct : ProductA
{
    //....
}

I'm trying to do an explicit cast from ProductA that is in a DLL I reference but it's telling me it's unable to cast

MyProduct myProduct = (MyProduct)productAobject;

Result:: System.InvalidCastException: Unable to cast object of type 'ExternalAssemb.ProductA' to type 'MyAssembly.MyProduct'.

What am I doing wrong?

Upvotes: 1

Views: 148

Answers (3)

Igor Zevaka
Igor Zevaka

Reputation: 76500

Quite simply, when you downcast, which may or may not succeed, you need to use is/as operators to check if the instance of ProductA is really MyProduct:

MyProduct myProduct = productAobject as MyProduct;
if (myProduct != null) {
  //valid MyProduct instance
} else {
  //productAobject is not really an instance of MyProduct 
}

Upvotes: 2

Steven Sudit
Steven Sudit

Reputation: 19620

You can cast a ProductA reference to a MyProduct reference, but only if it actually points to MyProductA or a child thereof.

What you're doing is trying to treat the parent like a child, that's doesn't work. Rather, you can treat the child like the parent, because it is like the parent.

Think of a generic example where a base class is called Shape and has children such as Square and Circle. Given a Shape reference, you can assign any child to it. But if the reference refers to a Circle, you can't cast it to a Square. This makes sense, because all circles are shapes, but no circles are squares.

Hope the examples help.

Upvotes: 5

Craig Walker
Craig Walker

Reputation: 51717

Every MyProduct is also a ProductA, but the reverse is not true. productAobject is an explicit instance of ProductA; it's not a MyProduct at all.

Similarly, given another class:

public class FooProduct : ProductA
{
    //....
}

...you could not do this:

ProductA myFooProduct = new FooProduct();
MyProduct myProduct = (MyProduct)myFooProduct;

...since FooProduct does not inherit from MyProduct.

The rule is: you can only cast an instance of a class to itself or one of its ancestor classes. You cannot cast it to any descendant or any other sibling/cousin class in the inheritance tree.

Remember that we're talking about the actual type of the instance here. It is irrelevant what the type of the variable that holds it is.

Upvotes: 1

Related Questions