Is there a way to have CodeDom put using statements before the namespace
Asked Answered
C

2

19

The msdn documentation says add namespaces imports to the CodeNamespace.Imports collection. This puts them inside the namespace (which makes sense, since your adding them to the namespace)

namespace Foo
{
  using Bar;

  //Code
}

However the rest of our code base has using statements outside the namespace:

using Bar;

namespace Foo
{
  //Code
}

Is there a clean way to get CodeDom to emit the second version?

Edit: the code to produce the first example looks something like this:

CodeNamespace ns = new CodeNamespace("Foo");
ns.Imports.Add(new CodenamespaceImport("Bar"));
CodeCompileUnit cu = new CodeCompileUnit();
cu.Namespaces.Add(ns);
new CSharpCodeProvider().GenerateCodeFromCompileUnit(cu, Console.Out, null);
Capua answered 4/5, 2010 at 13:43 Comment(0)
D
23

The simplest way is to add a global namespace entry into the Compile Unit (namespace without a name) and add the imports to it.

Demagnetize answered 2/2, 2011 at 17:15 Comment(1)
thank you; I had been wondering about this... a heartfelt +1 for the Frankenanswer, and also +1 for the spoooooky necrocomment praising the necro answer. :) and +♥♥ since it's the right time for spooky necro stuff and Frankenthings. ;)Pampa
O
8

So the code would be the same as before but with this bit added in.

CodeNamespace globalNamespace = new CodeNamespace();
globalNamespace.Imports.Add(new CodeNamespaceImport("Foo"));

// globalNamespace.Comments = string.Empty;    you cannot do this
ccu.Namespaces.Add(globalNamespace);
ccu.Namespaces.Add(ns);
Oogenesis answered 3/4, 2011 at 19:23 Comment(1)
the problem is that now I have an auto generated comment block at the beginningOogenesis

© 2022 - 2024 — McMap. All rights reserved.