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'.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With