Skip to footer content
Iron Academy Logo
C# Tools & Productivity

Creating Code Snippets in C# - Customize Visual Studio for Efficiency

Tim Corey
48m 46s

For developers working with C#, repetition is a reality. From writing properties to setting up console methods and catching exceptions, certain tasks can be streamlined. That’s where code snippets come in—small, powerful, reusable chunks of code that you can quickly insert into your project with just a shortcut.

In this article, we’ll explore how to create and use custom code snippets in Visual Studio, guided by expert C# trainer Tim Corey. In his video on "Creating Code Snippets in C# – Customize Visual Studio for Efficiency," Tim offers practical steps, commentary, and examples that you can apply directly to your own projects. By the end, you’ll be equipped to improve your productivity, write more readable code, and implement best practices across your development work.

Why Code Snippets Matter

Tim begins by sharing how he frequently uses snippets to insert things like auto-properties, constructors, and foreach loops. He demonstrates how typing cw and pressing Tab twice inserts Console.WriteLine(), placing the cursor between parentheses—an essential trick for string content output.

But as he points out, not every useful method has a built-in snippet. For example, Console.ReadLine() lacks one. Tim’s response? Create your own.

Setting Up a Demo Project in Visual Studio

To demonstrate in context, Tim sets up an ASP.NET Core web application in Visual Studio. Although the type of project isn’t critical, having C# and HTML files to work with lets him show examples from both languages.

This is a key reminder: snippets aren’t limited to C#—they can apply to multiple languages supported by Visual Studio, including HTML, XAML, and more.

Built-in Snippets and the Power of Shortcuts

Tim demonstrates a few existing snippets:

  • cw + Tab Tab → Console.WriteLine()

  • ctor + Tab Tab → Constructor

  • prop + Tab Tab → Auto-implemented property (e.g., public string Test { get; set; })

  • propfull → Creates a property with a backing field

These shortcuts are designed to eliminate repetition and increase performance. You just specify a type like string or int, a name, and let the rest auto-generate.

These built-in snippets can also demonstrate interpolation, access modifiers like public, and system-defined elements—ensuring your code follows consistent structure.

Creating Your Own Snippet in VS Code

Instead of using a snippet generator tool, Tim opts for Visual Studio Code because of its simplicity and XML syntax highlighting.

He creates a file named readline.snippet and shows the essential XML structure:

<CodeSnippets>
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Console.ReadLine</Title>
      <Shortcut>cr</Shortcut>
      <Description>Creates Console.ReadLine()</Description>
      <Author>Tim Corey</Author>
    </Header>
    <Snippet>
      <Code Language="csharp"><![CDATA[
Console.ReadLine();
]]></Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>
<CodeSnippets>
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Console.ReadLine</Title>
      <Shortcut>cr</Shortcut>
      <Description>Creates Console.ReadLine()</Description>
      <Author>Tim Corey</Author>
    </Header>
    <Snippet>
      <Code Language="csharp"><![CDATA[
Console.ReadLine();
]]></Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

This is a basic snippet, using <![CDATA[]]> to wrap the raw C# code. The shortcut cr now triggers insertion of the Console.ReadLine() method with two Tab presses.

Tim points out that the formatting is inherited from the user’s Visual Studio environment, meaning indentation and spacing will match your settings.

Importing Snippets into Visual Studio

Tim walks through how to import a .snippet file using Tools > Code Snippet Manager. He selects the My Code Snippets location, ensuring the snippet appears when needed.

Once imported, typing cr + Tab Tab inserts the Console.ReadLine() line, ready to assign its value to a variable or use within an exception handling block.

Reusable Documentation Headers

Next, Tim demonstrates a documentation snippet—a frequent need in enterprise projects or collaborative teams. He creates a snippet with the shortcut docme that generates a comment block:

/// Title:
/// Author:
/// Date:
/// Purpose:
/// Title:
/// Author:
/// Date:
/// Purpose:

This is ideal for tracking changes, authorship, and file context. While tools like Git handle versioning, headers offer quick visual references, especially in large teams.

HTML Snippets: Bootstrap Form Example

Snippets aren’t just for C# code. Tim shows how to use them in HTML—perfect for building forms, input elements, and collections of structured tags.

He copies a Bootstrap form example and wraps it in the same XML snippet format, changing the language to html. After importing, typing the shortcut sampleform inserts a ready-made HTML structure, saving you from repeatedly referencing external URLs or copying boilerplate.

Advanced Snippet with Placeholders and Variables

This is where things get more advanced—and more powerful. Tim builds a snippet that retrieves a configuration value:

_config.GetValue<string>("values:myTest");
_config.GetValue<string>("values:myTest");

He shows how to use placeholders for both the type (string, int, bool) and the path (values:myTest) so the developer only needs to fill in what's different.

In the XML, he uses:

<Declarations>
  <Literal>
    <ID>ValType</ID>
    <Default>string</Default>
    <ToolTip>Data type of the value</ToolTip>
  </Literal>
  <Literal>
    <ID>Path</ID>
    <Default>values:myTest</Default>
    <ToolTip>Config path</ToolTip>
  </Literal>
</Declarations>
<Declarations>
  <Literal>
    <ID>ValType</ID>
    <Default>string</Default>
    <ToolTip>Data type of the value</ToolTip>
  </Literal>
  <Literal>
    <ID>Path</ID>
    <Default>values:myTest</Default>
    <ToolTip>Config path</ToolTip>
  </Literal>
</Declarations>

In the snippet body:

_config.GetValue<$ValType$>("$Path$")
_config.GetValue<$ValType$>("$Path$")

This use of variables and declarations allows for flexible, expressive, and concise code generation. It’s ideal for tasks like security setting retrieval, dictionary access, or reading nested values from JSON files.

Why Snippets Improve Performance

Tim wraps up by explaining how snippets aren’t just about speed—they promote consistent practices, reduce errors, and improve team-wide code readability. Over time, even saving a few seconds per snippet can result in hours saved.

He emphasizes that snippets help with:

  • Common task initialization

  • Standardized exception handling with try-catch-finally

  • Creating entire class templates

  • Working within finally blocks, structured catch blocks, and method overrides

Final Thoughts: A Developer’s Edge

Whether you’re building complex systems or simple apps, code snippets can help you write C code or C# code faster and more consistently. They enable you to:

  • Eliminate repetition

  • Focus on business logic

  • Maintain a clean, interpolated, and well-documented codebase

As Tim suggests in his comprehensive video, explore your own coding habits. Discover where you type the same things over and over. Then, decide on one approach: create a snippet.

You’ll soon realize you’ve transformed your workflow—making development more efficient, organized, and enjoyable.

Quick Snippet Ideas to Get Started

  • tryfinally – Generate try + finally blocks

  • logerror – Insert logging logic with Log.Error()

  • propnotify – Property with INotifyPropertyChanged

  • filecheck – If File.Exists(path) with inline logic

  • foreachdict – Loop through a Dictionary<TKey, TValue>

Tim’s Tip: Don’t just copy-paste from another file—make it a snippet and never retype it again.

Hero Worlddot related to Creating Code Snippets in C# - Customize Visual Studio for Efficiency
Hero Affiliate related to Creating Code Snippets in C# - Customize Visual Studio for Efficiency

Earn More by Sharing What You Love

Do you create content for developers working with .NET, C#, Java, Python, or Node.js? Turn your expertise into extra income!