Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you automatically insert a namespace in a visual studio snippet?

I have a code snippet that creates a C# class for me. It puts the regions in all the right places and sets it up just the way I like it.

When I create a class by adding a new item it automatically creates the namespace based on my project and folder structure.

Is there a way I could do the same action with my custom snippet?

Is there a way I can change the default class to look like the class format I want?

like image 579
David Basarab Avatar asked May 04 '09 14:05

David Basarab


People also ask

How do I automatically add a namespace in Visual Studio?

If you are adding a new class in your code then you may need to add the correspondence namespaces. To do it, you may either manually type the Using Namespace or you just right click on the class name and select Resolve > Namespace. But using “Ctrl+.” you can automatically add the namespace in your code.

How do I add a code to snippet in Visual Studio?

With a code file open in the editor, choose Snippets > Insert Snippet from the right-click menu, then My Code Snippets. You should see a snippet named Square Root. Double-click it. The snippet code is inserted in the code file.

What is default namespace in Visual Studio?

Default namespace is the namespace that Visual studio sets when you create a new class. Next time you do Right Click > Add > Class it would use the namespace you specified in the above step.


2 Answers

This is possible now (2018), at least part of your's wishes, with adding this:

<Snippet>
  ...

  <Imports>
    <Import>
      <Namespace>SomeNamespace</Namespace>
    </Import>
    <Import>
      <Namespace>AnotherNamespace</Namespace>
    </Import>
  </Imports>
</Snippet>

For more info: https://github.com/dotnet/roslyn/issues/4457

like image 175
mojmir.novak Avatar answered Nov 15 '22 07:11

mojmir.novak


I do not think that this is possible with VS Snippets, there are only a few available functions, and they are listed at MSDN. You could, though, create a new Item Template and use the parameter $rootnamespace$, which will be replaced with the root namespace of the current project. Item templates are a really useful part of Visual Studio, and MSDN has extensive documentation on it and Visual Studio Magazine had a nice walkthrough about them.

like image 44
jakebasile Avatar answered Nov 15 '22 05:11

jakebasile