4

I want to force a root namespace on the contents of any .cs source files that don't have their contents wrapped in an explicit namespace. In other words I want to keep classes and other namespace-level structures out of the default namespace.
(Working inside a Windows .NET environment with Visual Studio)

In the following example, I want to force the Car class into the MotorIndustry namespace by default even though it has no explicit namespace coded.

Vehicle.cs (has namespace)

namespace MotorIndustry {
    public class Vehicle {
        // ...
    }
}

Car.cs (no namespace/default)

public class Car : Vehicle {
    //...
}

Is there a way to accomplish this "root namespace" modification behaviour through project settings in Visual Studio, AssemblyInfo.cs file or some other means?

My understanding is VB.NET has a feature like this but C# acts differently?

Some context about why am I asking this: I have hundreds of classes and the programmer forgot to wrap the namespace around some. When I reference the assembly from other projects it's polluting the default namespace with classes that end up causing some ambiguous situations.

John K
  • 28,441
  • 31
  • 139
  • 229
  • No, there is not the ability to globally namespace class files in C# as there is in VB.NET. John has your answer: third party refactoring tools. – Sky Sanders Feb 14 '10 at 03:32
  • I think the unique case of a Website project in Visual Studio (not a Web Application) tends to not generate namespaces for classes written under the App_Code special folder, or at least for user controls and pages, and I think this is where the problem started. Anyway, I've started wrapping everything in explicit namespaces even the user controls .ascx and asp.net pages for a more "strongly-typed" access to everything. It's much more manageable as the project grows. – John K Feb 15 '10 at 19:04

2 Answers2

5

Use ReSharper to move the classes into the proper namespace. In fact, version 5.0 (still in Beta) allows you to correct namespaces globally.


The other way to do it is to make the other developer fix the code.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • 1
    +1 @John: I'd make the other dev fix the code (*hint hint*) and run ReSharper anyway. – IAbstract Feb 14 '10 at 04:00
  • 2
    +1 don't try to accomodate a bad developer's sloppiness. next you'll need to find a way to make C# a case-insensitive language. – Josh Feb 14 '10 at 04:17
5

It sounds like you are trying to replicate VB.Net's project namespace feature in C#. This is not a supported feature of the C# compiler or IDE. You will not be able to create one by modifying a project file. You will need to add the namespace to every file in the project either manually or via a tool.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454