Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'.
like image 379
Shaku Avatar asked Nov 10 '13 02:11

Shaku


Video Answer


1 Answers

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.
like image 132
Daniel A.A. Pelsmaeker Avatar answered Oct 13 '22 01:10

Daniel A.A. Pelsmaeker