Suppose you had a code document represented by a FileCodeModel object. And suppose you were modifying the containing DOM. Sometimes, you might need to add a namespace import to the document (i.e. “using …” in C# of “Import …” in VB). A namespace import is represented by the CodeImport interface. Reading out the namespace imports is easy:
var imports = fileCodeModel.CodeElements.OfType<CodeImport>();
But how do you add a new CodeImport element? Well, TIL that it’s worthwhile to look at all versions of an automation interface (e.g. FileCodeModel2 instead of just FileCodeModel). Sometimes, you might find just the method you were looking for 🙂 So the answer to the question in this case is:
var fileCodeModel = (FileCodeModel2)projectItem.FileCodeModel; fileCodeModel.AddImport("My.New.Namespace");