19

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?

7 Answers 7

8

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)

Sign up to request clarification or add additional context in comments.

1 Comment

The extension is now: ***** PROJECT NO LONGER UNDER DEVELOPMENT *****.
7

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.

Comments

6

I have found these extensions that provide create C# class context menu option:

Comments

4

A moderately dirty solution with the current variable and regex system of vscode is the following:

Assuming that your have all your projects in /your/projects/directory/

So project #1 is in /your/projects/directory/Project1/
And project #2 is in /your/projects/directory/Project2/
etc.

The following snippet will create a namespace implementation for all sub-directories:

Linux/ MacOS

"Namespace declaration":
{
    "prefix": "name",
    "description": "Creates a new namespace declaration.",
    "body":
    [
        "namespace ${TM_DIRECTORY/^\\/your\\/projects\\/directory(\\/([^\\/]+))(\\/([^\\/]+))?(\\/([^\\/]+))?(\\/([^\\/]+))?(\\/([^\\/]+))?(\\/([^\\/]+))?(\\/([^\\/]+))?(\\/([^\\/]+))?(\\/([^\\/]+))?(\\/([^\\/]+))?/$2${3:+.}$4${5:+.}$6${7:+.}$8${9:+.}$10${11:+.}$12${13:+.}$14${15:+.}$16${17:+.}$18${19:+.}$20/gi}",
        "{",
        "}"
    ]
}

Windows

"Namespace declaration":
{
    "prefix": "name",
    "description": "Creates a new namespace declaration.",
    "body":
    [
        "namespace ${TM_DIRECTORY/^c:\\\\your\\\\projects\\\\directory(\\\\([^\\\\]+))(\\\\([^\\\\]+))?(\\\\([^\\\\]+))?(\\\\([^\\\\]+))?(\\\\([^\\\\]+))?(\\\\([^\\\\]+))?(\\\\([^\\\\]+))?(\\\\([^\\\\]+))?(\\\\([^\\\\]+))?(\\\\([^\\\\]+))?/$2${3:+.}$4${5:+.}$6${7:+.}$8${9:+.}$10${11:+.}$12${13:+.}$14${15:+.}$16${17:+.}$18${19:+.}$20/gi}",
        "{",
        "}"
    ]
}

Explanation

  1. The snippet matches your base directory and up to ten sub-directories (the first directory is mandatory (\\/([^\\/]+)), while all additional nine ones are optional (\\/([^\\/]+))?)
  2. The namespace directive is then created with the first matched directory
  3. For every successful additional sub-directory match, a dot . is inserted (${3:+.}) with the sub-match of that group ($4); for unsuccessful groups, no dot inserted and the sub-match is empty

Enjoy :)

1 Comment

Thanks for this solution. It works great for user snippets. If you want to share it with others working on the project, I suggest using WORKSPACE_NAME and RELATIVE_FILEPATH variables to remove dependency on the project path. "namespace $WORKSPACE_NAME.${RELATIVE_FILEPATH/([^\\/]+)(\\/([^\\/]+))?(\\/([^\\/]+))?(\\/([^\\/]+))/$1${2:+.}$3${4:+.}$5/i}",
1

Found this thread looking for the same answer.

I did not find any of the existing snippet suggestions to generate proper namespaces.
After some trial and error the closest I have gotten, using "variables" and "placeholder transformation", is:

    "Namespace and Class": {
        "prefix": "nclass",
        "body": [
            "namespace ${RELATIVE_FILEPATH/[\\\\]|\\w+\\.cs$/./g}$1",
            "{",
            "\tpublic class $TM_FILENAME_BASE\n\t{\n\t\t$0\n\t}",
            "}"
        ],
        "description": "Generates namespace and class name"
    }

This will generate a namespace from the folder structure in the workspace, and class name using the file name.

There is however an issue with this as it will leave two trailing .. at end of namespace. But cursor will stop there, so they can quickly be removed with a Ctrl + Backspace and then tab again to jump inside body of the class.

Comments

0

Use this one, first it focuses at the end of the namespace to add any additional section. Then it focuses inside the class.

"Namespace and Class": {
    "prefix": "nc",
    "body": [
        "namespace $WORKSPACE_NAME$1\n{\n\tpublic class $TM_FILENAME_BASE\n\t{\n\t\t$2\n\t}\n}"
    ],
    "description": "Generates namespace and class name"
}

Comments

0

Well, i was strugling with that too, but with all of the responses in this post i was able find the following solution:

"namespace ${RELATIVE_FILEPATH/(\\\\([^\\\\]+)$)|(\\\\)/${3:+.}/g} ;",

This will replace every backslash with a dot and remove the filename. Example: MyFolder\\SubFolder\\MyFile.cs will generate MyFolder.SubFolder

My Full Snippet File:

{
    "Default C# Class": {
    "prefix": "csclassstart",
    "isFileTemplate": true,
    "body": [
        "using System;",
        "",
        "namespace ${RELATIVE_FILEPATH/(\\\\([^\\\\]+)$)|(\\\\)/${3:+.}/g} ;",
        "",
        "public class ${TM_FILENAME_BASE} {",
        "    $0",
        "    public ${TM_FILENAME_BASE}(){",
        "    }",
        "}",
        ""
    ],
    "description": "C# class with dynamic class name and namespace derived from file name directories"
    }
}

How this works

Our goals are the following: (1) Remove the \\filename.cs from the RELATIVE_FILEPATH variable; (2) replace the double-backslashes (\\) with dots (.)

First we capture the filename by capturing everithing that matches the following:

  • double-backslashes \\\\
  • followed by something that isnt a backslash ([^\\\\]+)
  • followed by the end of the string $

This generates two capture groups

they are: (\\\\([^\\\\]+)$) and ([^\\\\]+) (the second is inside the first)

but we dont realy care about them, we just neet to keep count.

Then we use a OR | to capture a third group, witch is composed exclusively of double-backslashes (\\\\).

Finaly, we replace all captured groups with the following: ${3:+.} witch basically means,

if capture-group 3 is not empty, replace it with a dot (.).

With that, all double-backslashes will be replaced by dots, except the ones in \\filename.cs.

Thats happens because of the OR operator (|), witch will make this sequence will match the first capture-group and skip the third, making it empty and not triggering the replacement.

Because of that, is important to note that the order of the capture-groups is very important for this to wwork

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.