Reputation: 670
Suppose we have an interface:
interface ICustomShape
{
}
and we have a class that inherits from the Shape class, and implements the interface:
public class CustomIsocelesTriangle : Shape, ICustomShape
{
}
How would I go about casting a CustomIsocelesTriangle to a ICustomShape object, for use on an "interface level?"
ICustomShape x = (ICustomShape)canvas.Children[0]; //Gives runtime error: Unable to cast object of type 'program_4.CustomIsocelesTriangle' to type 'program_4.ICustomShape'.
Upvotes: 6
Views: 10555
Reputation: 50306
If you are sure that:
canvas.Children[0]
returns a CustomIsocelesTriangle
.
Use the debugger to verify, or print the type to the console:
var shape = canvas.Children[0];
Console.WriteLine(shape.GetType());
// Should print "program_4.CustomIsocelesTriangle"
You're casting to ICustomShape
(not CustomShape
).
CustomIsocelesTriangle
implements ICustomShape
.
Try this to verify (it should compile):
ICustomShape shape = new CustomIsocelesTriangle(/* Fake arguments */);
Then perhaps:
CustomIsocelesTriangle
in a different project or assembly, and you forgot to save and rebuild it after you made it implement ICustomShape
;ICustomShape
or two classes CustomIsocelesTriangle
(perhaps in different namespaces), and you (or the compiler) got them mixed up.Upvotes: 5