Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor dependency code snippet in visual studio

Tags:

c#

.net

I find myself adding dependencies a lot to constructors like so:

public class SomeClass() {
    private ISomeService _service;
    private IAnotherService _anotherService;
    public SomeClass(ISomeService service, IAnotherService anotherService) {
        _service = service;
        _anotherService = anotherService;
    }
}

They're quite tedious to write, I've been looking for code snippets in visual studio to automatically add one to the constructor but haven't found one.

What I want is:

  • When adding a dependency to a constructor some snippet automatically creates a local variable and assigns to it.

OR

  • Add a private variable and then some snippet automatically adds it to the constructor and assigns it to the local variable.
like image 900
Elger Mensonides Avatar asked Jan 21 '16 15:01

Elger Mensonides


People also ask

How do I find all available snippets for a dependency property?

For a dependency property, use propdp. You can find out all available snippets easily if you're using visual studio 2017: Type a letter, for example a. Click on the last icon at the bottom of the Intellisense Window. This displays all available snippets.

How to insert a snippet in Visual Studio Code?

In Visual Studio Code, snippets appear in IntelliSense (Ctrl+Space) mixed with other suggestions, as well as in a dedicated snippet picker (Insert Snippet in the Command Palette). There is also support for tab-completion: Enable it with "editor.tabCompletion": "on", type a snippet prefix (trigger text), and press Tab to insert a snippet.

How do I make a constructor in Visual Studio 2013?

For the full list of snippets (little bits of prefabricated code) press Ctrl+K and then Ctrl+X. Source from MSDN. Works in Visual Studio 2013 with a C# project. So how to make a constructor. Press Ctrl+K and then Ctrl+X. Select Visual C#.

How to assign a local variable to a constructor dependency?

When adding a dependency to a constructor some snippet automatically creates a local variable and assigns to it. Add a private variable and then some snippet automatically adds it to the constructor and assigns it to the local variable. Show activity on this post.


1 Answers

If you have R# you can enter the field declarations and then highlight them and hit Alt-Enter which will give you the option to generate the constructor and field assignments.

enter image description here

like image 194
NeddySpaghetti Avatar answered Oct 21 '22 10:10

NeddySpaghetti