Shaku
Shaku

Reputation: 670

C# - Casting an object to an interface

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

Answers (1)

Daniel A.A. Pelsmaeker
Daniel A.A. Pelsmaeker

Reputation: 50306

If you are sure that:

  1. 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"
    
  2. You're casting to ICustomShape (not CustomShape).

  3. CustomIsocelesTriangle implements ICustomShape.
    Try this to verify (it should compile):

    ICustomShape shape = new CustomIsocelesTriangle(/* Fake arguments */);
    

Then perhaps:

  • you have CustomIsocelesTriangle in a different project or assembly, and you forgot to save and rebuild it after you made it implement ICustomShape;
  • or, you reference an older version of the assembly;
  • or, you have two interfaces named ICustomShape or two classes CustomIsocelesTriangle (perhaps in different namespaces), and you (or the compiler) got them mixed up.

Upvotes: 5

Related Questions