Friday, May 20, 2011

CodeDOM -- generating an interface to a type

This is a fairly simple process -- reflect over the public properties and methods, and generate a matching interface member, rather like this:

which puts the required namespaces into order (TODO: sort System.* ahead of the rest).

The two functions look much the same, so could be factored further:

which special cases the indexer property; and

(TODO: generics and attributes, which I don't need for my immediate use case)

To make the code look less cluttered, to get type specifications which aren't fully namespace qualified everywhere, we want to specify types with keyword synonyms by type object, and the rest by name (with the namespaces included by using or open). So we have helper functions

where again, TODO handling generic types, especially collections, to get them looking pretty.

So if we use string as the type, and dump to C# we get

and in F#

where interestingly, the sorted order of the inserted members is reversed.

No comments :