How can I change the default namespace used when you create a new class in Visual Studio?
Background: My solution has a project MyCompany.MyProject.Domain in which I have a folder "Model Base (Linq)" with a subfolder "Extensions" where I keep all partial class extensions.
MyCompany.MyProject.Domain
+ Model Base (Linq)
+ Extensions
- Order.cs
- Trace.cs
When I create a new .cs file in there, the namespace gets set to MyCompany.MyProject.Domain.Model_Base\_\_Linq\_\_.Extensions, I only want it to be MyCompany.MyProject.Domain.Model though.
How can I change this default behavior?
To change the default namespace:
Right click on the project, go to properties and under the 'Application' tab there is a 'Default namespace' field.
Note that this doesn't answer your exact question though, it depends on your folder. You basically you need to rename that folder to 'Model'.
Resharper has changed how they do this (as of VS2017).
Now your folder is set to expect the namespace for all new classes. However, when you add a new class to the folder, it now complains that it's not the namespace that you set it to in step #3 above.
So, you still need to manually alter the namespace, but at least resharper isn't trying to fight you anymore.
If you already have one class under that folder with the desired namespace. You could take advantage of the
Move type to ClassName.cs
light bulb suggestion.For example, you created
Order.cs
with the correct namespaceMyCompany.MyProject.Domain.Model
under theExtensions
folder. If you want to addTrace
class you do it like so:Ctrl + .
when the edit cursor is anywhere around theclass Trace
words will show the suggestion.so...
Ctrl + .
Down
Down
Enter
Result:
There are 4 schools of thought here:
I tend to use the 4th; it is quicker than editing, and less hassle than changing the templates
If you have ReSharper installed, right click on the folder in your solution you want to be excluded from namespaces and select properties. In the properties pane, select
False
for Namespace Provider and that will make Visual Studio ignore the folder when generating namespaces in new files.