Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

codedom

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);
like image 532
Josh Sterling Avatar asked May 04 '10 13:05

Josh Sterling


People also ask

Should using directive be inside or outside the namespace?

As a rule, external using directives (System and Microsoft namespaces for example) should be placed outside the namespace directive. They are defaults that should be applied in all cases unless otherwise specified.

What is global namespace C#?

:: operator (C# reference) The global namespace is the namespace that contains namespaces and types that are not declared inside a named namespace.


1 Answers

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

like image 67
Thomas Mittag Avatar answered Oct 11 '22 08:10

Thomas Mittag