C# Obtaining Namespace Based on CSProj settings

880 Views Asked by At

Is there a way to obtain the .csproj Default Namespace and Visual Studios understanding it without using preprocessor directives?

For example:

CS Project 1 has a Default Namespace of SomeCompany.ProductA

CS Project 2 has a Default Namesapce of SomeCompany.ProductB

CS Project 1 has a cs file that exists in BaseClasses/MySpecialBase.cs

CS Project 2 has a linked file to that same file in the other project. This way maintaining one file version, without using different assemblies.

CS Project 2 now however has a cs file that references something from CS Project 1, so the class namespace would now be incorrect.

Is there a keyword that can be used in the single CS file to use the currently csproject file Default Namespace

IE: [MyDefaultNameSpace].BaseClasses

I would like to avoid doing #if #else if possible, so I don't have to add symbols.

namespace [somekeywordhere].BaseClasses
{
     class MySpecialBase
     {
        ....
     }
}
2

There are 2 best solutions below

1
On BEST ANSWER

No, there is no way to use the "Default Namespace" from within source code. It is used by the boilerplate T4 templates to automagically prepare new files, but it is a Visual Studio parameter and not an actual property of the code.

As you said, this can be done with some tricky usage of #ifs and symbols, or as DaveC said you could prepare a T4 template that generates the copy correcting the namespace (this would not use linking). In any case, this involves some work.

I see sort of an inversion of logical hierarchy when a deeper-level construct (your shared-by-linking file) uses something more specific (code from one or the other project), since I always used linked files to handle something like global version attributes or other assembly properties (e.g. company, product), so this shared file was never dependent on anything "logically above" it. But I guess you have your reasons, just making it clear.

1
On

Try using "Reflection API" - https://msdn.microsoft.com/en-us/library/ms173183.aspx for eg.

System.Type myNameSpaceAndClassName = this.getType()