Francesc Bosch
Francesc Bosch

Reputation: 77

C# Set namespaces easly in Visual Studio 2019

I have a C# project and I am mapping a lot of classes from Json models.

Some of the names are colliding so I have to setup namespaces every time. I generate the classes with an online tool to create C# classes from JSON, so by default the classes don't have a namespace.

Is there any way, with right click on the class or some tool on Visual Studio 2019, that allows me to automaticaly select a bunch of classes and set a namespace for them? Or right click a class and set it's namespace as it's path in the filesystem from the workspace folder?

The problem is that right now, my only chocie is copying the namespace, pasting it on every class and surrounding the code with brackets again and again. I just want to make this proces easier.

Also I know it's not needed to place every single class in a namespace, but to prevent execution time errors and keep the code sorted, I prefer to do so.

Upvotes: 1

Views: 943

Answers (3)

Hui Liu
Hui Liu

Reputation: 1038

@ Francesc Bosch.

For changing the namespace of an existing class, you can right click on your current namespace and select Rename -> change to your new namespace-> click Apply.

If you have multiple depths of the namespace, Visual Studio will not allow you to type dots. However, if you copy and paste a dot, it will succeed despite the warning.

You could also move the class to the changed target namespace.

1.Right-click the name of the class you want to move -> select Quick Actions and Refactorings... -> click Move to namespace...

enter image description here

2.In the dialog box that opens, select the target namespace you'd like to move the type to.

enter image description here

Upvotes: 1

Abhijeet
Abhijeet

Reputation: 13856

You can user Resharper to adjust namespaces of existing classes. https://www.jetbrains.com/help/resharper/Fix_inconsistent_namespace_naming.html enter image description here

Upvotes: 2

silentw
silentw

Reputation: 4885

You can Paste JSON As Classes in Visual Studio.

Paste JSON As Classes

It will create the classes with the current namespace. Simply create a new class, "Paste JSON As Classes" and it will create every model from the JSON on the clipboard.

Upvotes: 3

Related Questions