Accessing methods from interface after creating object from Activator.CreateInstance

Viewed 59

How do I access the interface implementations from an object?

interface IGraphicsObject
{
    Draw();
    Delete();
}

I create 3 classes: Square, Circle and Triangle, all implementing IGraphicsObject. Then I do something like

object Shape = Activator.CreateInstance("myShapes", "Square");

Then I want to be able to type:

Shape.Draw();
Shape.Delete(); 

etc.

How do I do that?

2 Answers

Cast to IGraphicsObject

IGraphicsObject Shape = (IGraphicsObject)Activator.CreateInstance("myShapes", "Square");

With the created instance now, you can invoke the interface methods

Shape.Draw();
Shape.Delete(); 

The simple answer is to typecast it, but you can do it a bit better by:

    public interface IGraphicsObject
    {
        void Draw();
        void Delete();
    }

    public class Square : IGraphicsObject
    {
        public Square(string mysharpes, string square)
        {
        }

        // fill out...
    }

    public class Circle : IGraphicsObject
    {
        public Circle(string mysharpes, string square)
        {
        }

        // fill out...
    }

    public class Triangle : IGraphicsObject
    {
        public Triangle(string mysharpes, string square)
        {
        }

        // fill out...
    }

    public class Main
    {
        public IGraphicsObject CreateInstance<T>(string mysharpes, string square) where T : IGraphicsObject
        {
            return (IGraphicsObject) Activator.CreateInstance(typeof(T), mysharpes, square);
        }

        public void Run()
        {
            var shape1 = CreateInstance<Square>("mysharpes", "square");
            var shape2 = CreateInstance<Circle>("mysharpes", "square");
            var shape3 = CreateInstance<Triangle>("mysharpes", "square");

            Draw(shape1,shape2,shape3);
        }

        public void Draw( params IGraphicsObject[] shapes )
        {
            foreach( var shape in shapes )
               shape.Draw();
        }
    }

So you ensure that only types that implement the interface is allowed for the typecasting creation method.

Related