locked
Proves on dynamically implementing C# interfaces RRS feed

  • Question

  • I'm trying to find a sort of proves of that is not possible implement dynamically an interface

    that is create a factory that allows the following:

                 IFoo myFoo = (new Factory<IFoo>()).Create();

    With DLR we can create an object with the IFoo's members but the cast give us a runtime exception.

    I do the same question on stackoverflow:

    http://stackoverflow.com/questions/12496837/dynamically-implementing-c-sharp-interfaces-possible-or-not

    Thanks.

    Wednesday, September 19, 2012 2:48 PM

Answers

All replies

  • I have made a factory which takes an interface as type parameter and returns an object implementing that interface. In SO, you add "without emitting code". How do you expect to implement the interfaces methods?

    Wednesday, September 19, 2012 3:37 PM
  • What do you want the Factory<T> to do?  

    There are options here outside of generating code on the fly (which you seemed to want to restrict) - including using something like a service locator or IoC to find an appropriate implementation of IFoo, and return that, etc.  It depends on what the goal is...


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Wednesday, September 19, 2012 4:04 PM
  • Thank for the answer Reed Copsey.

    It's not about Inversion of Control. My problem is the following I realize that I can create a factory that crates an object with the members that I want, for example CompareTo method but later I can not use this object as a IComparable. I know that the C# runtime give us an exception at the casting's moment. So, I am finding an convincent argument of what that is not possible.

    Wednesday, September 19, 2012 6:39 PM
  • An interface in C# (.NET) isn't about just providing the proper methods and properties - you still have to implement the interface explicitly in order for it to work.  C# does not support duck typing for interface implementation - the returned object must explicitly implement the interface in order to work as that interface.


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    Wednesday, September 19, 2012 9:10 PM
  • To have a dynamically generated class implement an interface, you need to call AddInterfaceImplementation.

    That's what I did here: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/0b9c6aaa-f880-41d9-9ec0-230d7fcd4aef

    A p/invoke method cannot implement an interface method, so I had to emit code to call one from the other.

    • Proposed as answer by Jason Dot Wang Friday, September 21, 2012 5:43 AM
    • Marked as answer by Jason Dot Wang Thursday, September 27, 2012 8:15 AM
    Thursday, September 20, 2012 9:47 AM