Inserting the Class Name in a Code Snippet

Code snippets allow boilerplate code to quickly be inserted in code editors. Snippets can include replacements to allow the developer to modify snippet text and functions that generate code. The ClassName function adds the name of the current class.

Code Snippets

In previous articles we have seen how you can create and register custom code snippets and add them to your project's code using Visual Studio. We have also investigated the use of replacements that create placeholders that can be overwritten with assistance from the integrated development environment (IDE). In this article we will introduce a code snippet function.

ClassName Function

Code snippets can include literals that can be used with overwriteable placeholders. They can also include a number of functions that generate code according to the position at which they are added, or in response to information provided by the programmer. An example function is ClassName. This inserts the name of the class in which the snippet is inserted.

In a previous article we saw a snippet that inserted all of the code for the basic IDisposable pattern but without a finalizer. The finalizer could not be added automatically because the name of its method includes the name of the class. In this article we will create the full IDisposable implementation in a code snippet using the ClassName function to generate the finalizer name.

Creating the Snippet File

The XML for the code snippet is shown below. There are several differences when compared to the original IDisposable snippet. The first is that the Shortcut value has been changed to "idispf". This will allow you to register the snippet alongside the original, which used "idisp".

The second change is in the Declarations section of the XML. A Literal element is defined to hold the details that will be inserted into the code. As with standard replacements, a unique ID for the literal and a ToolTip have been defined. In addition, the Function element holds the name of the function used to generate the code for the placeholder. For the ClassName function this is "ClassName()". Note that the Editable attribute of the literal is set to false. This optional value prevents the ability to tab to the placeholder and overtype its value.

Finally, a placeholder for the literal has been added to the code as $classname$. Combined with a tilde character (~), this creates the name of the finalizer method. The placeholder will be replaced with the class name on insertion of the snippet.