Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VSCODE snippet for creating new C# class with namespace declaration

For now we are able to create only new file or folder. And it's very annoying to write namespaces each time you create class declaration.

But is it possible to create new C# class file with auto generated appropriate namespaces inside? Or maybe some snippet there?

like image 770
Andrii Tsok Avatar asked Nov 02 '15 19:11

Andrii Tsok


People also ask

How do I create a code snippet in VSCode?

Create your own snippets# To create or edit your own snippets, select User Snippets under File > Preferences (Code > Preferences on macOS), and then select the language (by language identifier) for which the snippets should appear, or the New Global Snippets file option if they should appear for all languages.

What is C snippet?

Snippet is a programming term for a small region of re-usable source code, machine code, or text. Ordinarily, these are formally defined operative units to incorporate into larger programming modules. Snippet management is a feature of some text editors, program source code editors, IDEs, and related software.


2 Answers

This extension provides a context menu button to add a new class, which will auto populate the namespace.

Visual Studio Code has changed a bit since the last answer. It now provides the variable TM_DIRECTORY in snippets, but this is an absolute path. I've submitted an enhancement request to provide a relative path that could be transformed to a namespace. But honestly, I think the above extension satisfies my needs (and the context menu is a plus)

like image 101
mdickin Avatar answered Sep 18 '22 15:09

mdickin


That's currently not possible. You have no possibility to retrieve the current filename, directory or other information in a snippet declaration file for Visual Studio Code.

You could create a snippet that lets you enter a namespace and a class name. But I guess this wouldn't help you so much. Nevertheless it'd look like this:

 "Namespace and class": {
    "prefix": "namespaceAndClass",
    "body": [
        "namespace $1",
        "{",
        "   class $2",
        "   {",
        "",
        "   }",
        "}"
    ],
    "description": "Create a namespace block with a class"
 }

In case you really want a snippet that fills in the correct namespace and class name based on the file path you could have a look at the OmniSharp project. This can give you an idea on how to improve the csharp-o extension in order to provide the correct data as a suggestion from within the plugin. But I think this is a much bigger task then typing namespace and class on your own.

like image 41
Wosi Avatar answered Sep 19 '22 15:09

Wosi