Have you ever found yourself in the situation where you know what you want your program to do, but you just don’t know how to express it in code? If so, then read on. If not, read on anyway, as this still may be of use to you!

Code snippets are an excellent feature of visual studio, especially if you go to the effort of learning the shortcuts.

They most important shortcut to remember is Ctrl-K, Ctrl-X (multiple shortcuts used like this is known as a chord). This should bring a code snippets UI. Next I press V for Visual C# and then you can select or type the keyword of a load of constructs and code snippets will deal with the syntax for you. Any variables or names that you might want to define can then be tabbed through.

Hello, Code Snippets!

Here’s an example of a function created using snippets:

public void SortList(List<int> pValues)
{
  bool swaps = false;
  do
  {
    for (int i = 0; i < pValues.Count - 1; i++)
    {
      if (pValues[i] > pValues[i+1])
      {
        int temp = pValues[i];
        pValues[i] = pValues[i + 1];
        pValues[i+1] = pValues[i];
        swaps = true;
      }
    }
  } while (swaps);
}

And here are the parts of that code that were written using code snippets:


  do
  {
    for (int i = 0; i < pValues.Count - 1; i++)
    {
      if (pValues[i] > pValues[i+1])
      {

      }
    }
  } while (swaps);

Code snippets are particularly useful for developing in languages that you are not familiar with. Often you know what you want to do, but you don’t know the correct syntax. In these cases code snippets are invaluable. Here’s the same code, but this time written in Visual Basic, which I hardly ever use:

  Dim swaps As Boolean = False
  Do
    For index = 1 To pValues.Count - 1
      If pValues(index) > pValues(index + 1) Then
        Dim temp = pValues(index)
        pValues(index) = pValues(index + 1)
        pValues(index + 1) = pValues(index)
        swaps = True
      End If
    Next
  Loop While swaps

The logic is the same, but the syntax is different. If you’re ever unsure of the syntax you should be using to get something to work remember Ctrl X, Ctrl K and code snippets will help you out!

You can even define your own snippets, but I’ll save that for some other day.