Code snippets, in general, are small pieces of code that often can’t be used separately, but they’re rather intended to be integrated in a larger solution. Visual Studio offers several features for working with snippets, and because Dynamics AX development is now done completely in Visual Studio, X++ developers can use them too.
Let’s start with something trivial. Open X++ code editor (e.g. create a runnable class), open context menu (right click) there and select Insert Snippet. Notice the keyboard shortcut (Ctrl+K and then X); it’s very handy if you use snippets more often.
You’ll get a list of available snippets. Choose ctor (constructor) for now:
This inserts source code for a constructor at current cursor position.
Although pasting a static piece of code can be useful, it’s not very exciting. Let’s look at the For snippet instead:
For now, put the snippet directly to the class definition, not inside a method. There is a certain problem that could lead to incorrect behavior – it’s explained in detail in a separate post.
This will create a for loop, but that’s not all. Notice that there is i variable, used at three places, and that the first occurrence is selected:
You can immediately start typing and change the name; press Tab when you’re done. All three occurrences of i change to the new name and the cursor moves to the next place that you likely want to change – the condition.
This is really helpful – you don’t have to manually change the same thing several times and you’re navigated directly to those places you should change, ignoring static parts. Also don’t forget that this is just a simple demonstration – you can use the same approach for much more complex scenarios.
Another thing you can do is to put a snippet “around” a selected piece of code. For example, let’s say that I’ve just realized that I need exception handling for my code. I select the code and choose Surround With from the context menu:
Then I pick the try snippet, which puts my code into a try block and I can immediately start writing my exception handling logic.
We have editor scripts in MorphX IDE, but they aren’t as easy to use as they should be. Code snippets in Visual Studio are a welcomed, powerful improvement.