1

In C#, is it possible to use a handwritten interface for a dynamic var? I'm interfacing with an app using COM automation, and although I can access properties like this:

dynamic shape = comObject;
int Width = (int)shape.Width;

..I would really prefer to use this:

interface PageShape {
   int Width {get; set;}
   int Height {get; set;}
}
PageShape shape2 = (PageShape)comObject;

int Width = shape.Width; // COOL!

Is this possible? This typically triggers an InvalidCastException, but I'm just curious to see if its possible. More details on my specific scenario here.

Community
  • 1
  • 1
Robin Rodricks
  • 110,798
  • 141
  • 398
  • 607
  • possible duplicate of [Implementing an Interface at Runtime](http://stackoverflow.com/questions/16802712/implementing-an-interface-at-runtime) – lightbricko Dec 28 '13 at 22:24

2 Answers2

2

Since you can't access the original code you'll have to add in your own layer. You won't be able to get around the transforming from dynamic to an actual interface as far as I know, but you can do this transforming in one layer and use actual OOP afterwards.

This could be a sample implementation:

void Main()
{
    IPageShape pageInfo = ComTransformer.GetPageShape(comObject);
}

interface IPageShape {
   int Width { get; set; }
   int Height { get; set; }
}

class PageShapeImpl : IPageShape {
    public int Width { get; set; }
    public int Height { get; set; }
}

static class ComTransformer {
    public static IPageShape GetPageShape(dynamic obj) {
        return new PageShapeImpl {
            Width = (int) obj.Width,
            Height = (int) obj.Height
        };
    }
}
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
  • @Geotarget: yes, pretty much. You wrap the transforming of the objects in a utility class to make the transforming easily accessible troughout the project and keep the logic to do so grouped together. A [quick search](http://stackoverflow.com/questions/2974736/dynamically-implementing-an-interface-in-net-4-0-c) reinforced my feeling that there is no possibility to do this without explicitly transforming the objects yourself. -- Edit: nevermind, explicit convertors won't work. – Jeroen Vannevel Dec 28 '13 at 21:31
0

dynamic does not make the actual object dynamic, unless it is a dynamic object, it just tells the compiler to resolve the variable at run time.

So if the object in the dynamic variable is an object that implements an interface it will work, if not you will get a cast exception

For example this will work on the first but not on the second call:

interface ITheInterface{}
class TheClass : ITheInterface{}
class OtherClass {}
public static void Main(string[] args)
{ 
    NextMethod(new TheClass());
    NextMethod(new OTherClass());

}

public static NextMethod(dynamic d)
{
    //works on the first call but not the second
    TheInterface ti = (ITheInterface)d;

} 
konkked
  • 3,161
  • 14
  • 19