C # - Dynamic keyword and interface implementation

I guess this is not possible, but before digging further, there is a way to do something like this:

public void ProcessInterface(ISomeInterface obj) {}

//...

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

      

I saw the post , but it looks like it was not enabled.

Small context: .Net assembly exposed via COM-> Silverlight application using classes that implement the interface. It would be nice to refer to objects by interface. I really don't expect this to be what was intended ...

+2


a source to share


3 answers


No, dynamic

it won't make the type pretend to implement the interface (even if it has, via dynamic

, all methods). Passing it in ProcessInterface

essentially takes away dynamic

.

dynamic

depends on the calling code as well as on the implementation object. More, even.



However, you can create an interface wrapper that uses duck printing:

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();
}

      

+6


a source


I don't think I understand your point. If you know the exact interface you are dealing with, why would you need to use dynamic

?



+2


a source


You can use the opensource Impromptu-Interface for this. This is an automatic way to skin an interface and uses DLR.Impromptu.ActLike<ISomeInterface>(myDyn)

+2


a source







All Articles