Search code examples
c#namespacesclass-design

Can I force a dependency between namespaces in C#


Can I restrict classes from a specific namespace from referencing classes in another specific namespace? Both namespaces exist in the same .NET assembly.

Example:

namespace LegacyCode
{
    class LegacyClass { ... }
}

namespace NewCode
{
    class NewClass {...}
}

I do not want classes from 'NewCode' to be able to reference classes in 'LegacyCode'.

Options:

  1. Have different assemblies (makes deployment harder, build takes longer)
  2. Using a tool like NDetect (costs money!)

Does anyone have any other ideas?


Solution

  • Consider marking the classes with the Obsolete attribute. This will cause any code that isn't itself marked as 'Obsolete' to generate a warning during compilation.

    Enable 'Treat warnings as errors' setting on the 'Build' tab of the project file to cause this warning to fail compilation with an error instead.

    Edit:

    Agree that seperate assemblies is a good strategy to facilitate fading out this code. This won't stop people referring to it though. The obsolete attribute makes it clear that this code is, um, obsolete.

    Edit #2:

    Thanks to Dan Tao for pointing out the overloaded constructor of the Obsolete attribute. This means you can enforce whether usage of a something should be treated as an error or not, without having to enable treat warnings as errors. There is also usefully the option to specify a message instructing the user of a workaround. This message is displayed during compilation in the error/warning.