Make a Mutable Copy of an Immutable Representation

CCI Metadata

To modify an immutable representation, you must make a mutable copy and work with the copy. For example, applications often start with an existing assembly and use a PeReader object to parse the assembly and construct an object model. The following example from the FindGeneric sample uses PeReader.DefaultHost.LoadUnit to load an assembly from a file and return an object model representation.
IAssembly/*?*/ assembly = host.LoadUnitFrom(assemblyName) as IAssembly;

PeReader constructs an immutable representation of the assembly, which is sufficient for applications that examine the assembly’s contents but do not modify the assembly. FindGeneric, for example, simply looks through the assembly for generic methods and displays the results.

To change the assembly in any way, you must have a mutable representation. To do this, create a MetadataMutator object and pass the immutable version of the assembly to the MetadataMutator.Visit method. Visit traverses the immutable version of the assembly and uses the data to create a mutable copy of the original. In programming terms, you pass Visit an IAssembly interface, and it returns an Assembly object that is a copy of the original. You can then modify the Assembly object as you wish.

Last edited Mar 17, 2010 at 3:19 PM by Guy_Smith, version 3


No comments yet.