Linked by Rüdiger Klaehn on Thu 5th Aug 2004 05:00 UTC
.NET (dotGNU too) One of the most awaited features of Microsoft .NET 2.0 is generics. Generics promise to increase type safety, improve performance, reduce code duplication and eliminate unnessecary casts. The most obvious application of generics in the framework class library are the generic collections in the new System.Collections.Generic namespace. Much has been written about those, but they are not the topic of this article.
Permalink for comment
To read all comments associated with this story, please click here.
Implicit Interfaces
by Rich on Thu 5th Aug 2004 13:03 UTC

I came up with a similar implicit interface idea a couple of years ago, but mine didn't involve any extra syntax (i.e. more like C++). The compiler knows about the requirements of the parameter types for a generic type when it compiles the generic type, so it could compile in an implicit interface without the developer ever having to know about it. For generic classes that can get by with just System.Object operations, no interface would be required. For those requiring just the basic numeric operations, the compiler would compile a special-case generic class for the arithmetic types (polymorphic IL opcodes mean just one should be required) and a separate case generic with an implicit interface having the required overloaded operators. The compiler, upon compiling the instantation of a generic type, knows exactly what the capabilities of the parameter type are, just as in C++ and in the current C# generics, so ensuring the match against the required interface should be no problem, just as it is now for explicit constraints. Because the parameter type may be used in the generic instantiatiation separately from its definition (i.e. separate assembly), regular interface specification won't always be possible. There are a number of solutions which don't require engine modification, such as using wrapper classes, delegates, and reflection.emit.

The best solution, IMO, however, is to extend IL so that the instantating assembly can specify that the parameter type implements the implicit interface, and to modify the engine so that it can perform the interface mapping after the initial loading of the type. The engine already has to be able to generate vtables for interface-implementing classes which hook up method bodies to interface methods; it just needs to be made flexible enough to perform the mapping on demand rather than just at its initial type loading. This on-demand approach would also work well for purely dynamic types, both as generics and their parameters, and would incur no excessive overhead as would be required by purely compiler-based approaches. Perhaps I'm overlooking something, though; if so, please let me know.


Rich