views:

113

answers:

2

I'm assuming this isn't possible but before digging further is there a way to do something like this:

public void ProcessInterface(ISomeInterface obj) {}

//...

dynamic myDyn = GetDynamic<ISomeInterface>() 
ProcessInterface(myDyn);

I've seen a post arguing for it but it sounds like it wasn't included.

A little context: .Net assembly exposed through COM -> Silverlight app consuming interface-implementing classes. Would be nice to refer to the objects by interface. I really don't expect that this was what was intended...

+1  A: 

I don't think I understand your point. If you know the exact interface you're be dealing with, why do you need to use dynamic?

Fyodor Soikin
True, but I was wondering if it was even possible.
Adam Driscoll
+3  A: 

No, dynamic won't make a type pretend to implement an interface (even if it has, via dynamic, all the methods). Passing it to ProcessInterface essentially takes away the dynamic.

dynamic depends on the calling code just as much as the implementing object. More, even.

You could however make an interface wrapper that uses duck typing:

class Foo : IBar {
    readonly dynamic duck;
    public Foo(dynamic duck) { this.duck = duck; }

    void IBar.SomeMethod(int arg) {
        duck.SomeMethod(arg);
    }
    string IBar.SomeOtherMethod() {
        return duck.SomeOtherMethod();
    }
}
interface IBar {
    void SomeMethod(int arg);
    string SomeOtherMethod();
}
Marc Gravell
That's kind of what I expected. I think whenever my code get hacky ideas like this pop into my head...
Adam Driscoll
@Adam - see also the hacky idea that I added..
Marc Gravell
That would sure elevate my hack level...Now to write some code to emit Foo at runtime...
Adam Driscoll
@Adam - I don't recommend it - those `duck.SomeMethod(arg)` etc calls are **scary** if you look at them in reflector.
Marc Gravell
Haha I was just kidding :)
Adam Driscoll