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?
You can cast a
ProductAreference to aMyProductreference, but only if it actually points toMyProductAor 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
Shapeand has children such asSquareandCircle. Given aShapereference, you can assign any child to it. But if the reference refers to aCircle, you can’t cast it to aSquare. This makes sense, because all circles are shapes, but no circles are squares.Hope the examples help.