Inferred interface implementation RRS feed

  • General discussion

  • I remember before .NET 4.0 was released, there was talk of "contracts" as a CLR feature, and the way I understood it, it would have been basically like "inferred" interface implementation - what that is, I'll get to in a moment! Of course this feature was not actually implemented in .NET 4.0, but I would like to see it in a future .NET release!

    Anyway, what do I mean by inferred interface implementation? Well, imagine this scenario:

    You have some classes in a DLL somewhere (say, part of the .NET Framework, or from some third party vendor), and you want to categorize the classes based on their functionality into interface types that YOU have defined. Now you can't do this in .NET, because interfaces are "baked in" at compilation, and can't be applied retroactively to existing classes!

    For instance, suppose you had an interface, IStringifiable (silly name but bear with me here) which has only one method, ToString(). Now of course every .NET class implements ToString(), since it's defined in System.Object. But if you try to cast some existing to IStringifiable, you get an invalid cast error, because when the object's class was created, it had no idea of IStringifiable!

    This problem makes it harder to work with existing classes for which you don't have the source code, since if you want to abstract away some of the functionality in a way that the class author didn't think of, you have to either duplicate methods (this version of the method takes a UssEnterpriseNcc1701, the other version takes a MillenniumFalcon, why didn't they put in an ISpaceship interface?!) or write adapter classes on top of the existing classes.

    So, essentially, what I'm saying is, can we get in some future version of the .NET Framework this "inferred interface implementation" feature I've described? Essentially all it is is, if some class implements all the methods/properties/events with all the proper signatures for some interface, it should be possible to treat the class as if it implemented the interface.

    Mr. Flibble says... game over, boys!
    Thursday, December 8, 2011 4:09 AM

All replies

  • You basically get this behavior with dynamic, as it creates a "runtime" bound interface you can write code against.  By using dynamic and setting a dynamic variable to a type, you can call any method on it, without requiring the interface to be "baked in" at compile time.


    I suspect the discussions you are referring to, however, probably deal with the NOPIA features in .NET 4, which allow for type equivalence in COM interfaces... This was implemented, and dramatically helps with COM interop development.


    Reed Copsey, Jr. -
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    Thursday, December 8, 2011 5:53 AM