C# Snippets

Prop snippet: Visual Studio screenshot

Snippets are a useful feature in the Visual Studio IDE. With them, you can type a few letters and then press tab twice to insert a code fragment. They help reduce repetitive statements and can reduce overuse injuries with your hands.

Ctor

First, the ctor snippet is available in Visual Studio 2010. To use ctor, place the cursor inside a class body. Then, type the four letters 'ctor' and press tab twice. This article shows what happens after you press TAB TAB.

Where to use ctor snippet: press tab tab

class Example
{
    ctor
}

class Program
{
    static void Main()
    {
    }
}

Result

class Example
{
    public Example()
    {

    }
}

class Program
{
    static void Main()
    {
    }
}
Programming tip

Adding parameters. The snippet inserts a parameterless public constructor, which is probably the most common type. However, if you want to add parameters, simply add them inside the parentheses manually.

Tip:If you want multiple constructors, just add more in the same way with this snippet.

Constructor

Class

Class

With the class snippet you insert a new class. You must type the keyword "class" and press tab and then tab again to insert the class definition. The default name will be MyClass. You can then rename this to a more appropriate identifier.

Tip:You can use the class snippet anywhere in a file, but you should only use it in a place where a class can be declared.

Where to use class snippet: press tab tab

class Program
{
    static void Main()
    {
    }
}

class

Result

class Program
{
    static void Main()
    {
    }
}

class MyClass
{

}

The class snippet allows you to instantly insert the class definition with correct syntax in your C# program. This can be useful if you create many classes in your projects. You can find more information on classes on this website.

Class Modifiers, Syntax and Concepts

Cw

Console screenshot

In a place where you want to insert a call to Console.WriteLine(), type cw and press TAB twice. The letters 'cw' will be expanded to "Console.WriteLine()". If the System namespace is required, it will be used.

Where to use cw snippet: press tab tab

class Program
{
    static void Main()
    {
	cw
    }
}

Result

class Program
{
    static void Main()
    {
	System.Console.WriteLine();
    }
}

After typing cw and then TAB TAB, the caret will be positioned inside the parentheses, so you can immediately start specifying the arguments. For developers working on large console programs, this is useful for saving a few keystrokes.

Do

Do keyword

To use the do snippet,
type the word "do"
and then press tab twice. This will insert do-while code into your program at that position. The "true" will be highlighted so you can change it easily, without repositioning yourself.

Where to use do snippet: press tab tab

class Program
{
    static void Main()
    {
	do
    }
}

Result

class Program
{
    static void Main()
    {
	do
	{

	} while (true);
    }
}
Note

Of all the loop constructs in the C# language, the do-loop has the shortest initial keyword. However, if the entire loop structure is too verbose for you, the do snippet can come in handy.

Lock

Lock keyword

The lock snippet can be useful. This program has a static object added to it that we can use in the lock statement. Type the string "lock" and press the tab key twice. The resulting program will contain the lock(){} statement.

Tip:You must replace the object to be locked upon with the best object. Here, we use the _locker object.

Where to type the lock snippet: C#

class Program
{
    static object _locker = new object(); // Lock on this object!

    static void Main()
    {
	lock
    }
}

Resulting program: C#

class Program
{
    static object _locker = new object(); // Lock on this object!

    static void Main()
    {
	lock (_locker)
	{

	}
    }
}
Question and answer

When to lock? This is not a good real-world example of using the lock statement. For more information on the lock statement, including a broader conceptual view, visit the specific article on this site.

Lock Statement

Tip:Don't forget to use the lock statement when the possibility of data corruption is present because of multiple concurrent threads.

And:Having a lock statement can mean the difference between a program that works correctly and one that fails at unexpected times.

Mbox

Visual Studio logo

With mbox you can insert a simple method call with only a few keystrokes. Type the letters "mbox" into your program. Typically, you will be doing this in a Windows Forms program, but you can use MessageBox.Show in any .NET program.

And:After typing "mbox", press tab twice. You can see in the second part of the example that a call to MessageBox.Show was generated.

Where to use mbox snippet: C#

class Program
{
    static void Main()
    {
	mbox
    }
}

Result of the snippet

class Program
{
    static void Main()
    {
	System.Windows.Forms.MessageBox.Show("Test");
    }
}

Tip:If you try to compile the output program in a console program, you will get a compile-time error.

Add reference:Right click on References and go to Add Reference. Click on ".NET" and then click OK on System.Windows.Forms in the dialog.

The mbox snippet allows you to insert a call to the MessageBox.Show method. You can use this snippet in any C# program inside Visual Studio, but it is most useful in Windows Forms programs.

System.Windows.Forms

Prop

Next we use the prop snippet in Visual Studio. To begin, place the cursor somewhere in the scope of a class, where you want to put your property. Type prop and then press tab twice. Next, Visual Studio will select the 'int' keyword.

Note:You can change this to any type you want. It is a good idea also to change the name from MyProperty to something more descriptive.

Property
Where to use prop snippet: press tab tab

class Program
{
    prop

    static void Main()
    {
    }
}

Result

class Program
{
    public int MyProperty { get; set; }

    static void Main()
    {
    }
}

The 'prop' snippet in Visual Studio is useful for creating automatically implemented properties. Because the just-in-time compiler optimizes properties, they are typically as fast as field accesses but slower than local variables.

JIT Method Test

Propfull

Property

Here we see the propfull snippet in Visual Studio. To begin, put your cursor on a line in the scope of a class. Type propfull and press tab twice. The keyword 'int' will be highlighted.

You can change this to another type of your choosing. When you press tab after making the change, the type will be matched in the property itself. Finally, change the MyProperty to a more descriptive identifier.

Where to type propfull: press tab tab

class Program
{
    propfull

    static void Main()
    {
    }
}

Result of the snippet

class Program
{
    private int myVar;

    public int MyProperty
    {
	get { return myVar; }
	set { myVar = value; }
    }

    static void Main()
    {
    }
}

The 'prop' snippet provides an automatically generated property member. And the 'propfull' snippet inserts the code for the more verbose syntax form. You may need to use a full property because of a requirement for special code.

Sim

Method call

The sim snippet refers to static int Main. To get started, find a place where you want to insert the Main method. Type sim and then press tab twice. A static int Main method with a string[] formal parameter will be inserted.

Where to type sim snippet: press tab tab

class Program
{
    sim
}

Result

class Program
{
    static int Main(string[] args)
    {

	return 0;
    }
}

As with several other snippets, the sim snippet is not likely to be useful often. However, it is an interesting example of providing textual shortcuts (aliases) for software development. The term 'sim' abbreviates "static int Main".

Svm

Void keyword

Next, we use the svm snippet. First position your cursor in a class and then type svm and press tab twice. The static void Main method then appears. You can now type statements inside the Main entry point.

Main Args ExamplesVoid Type
Where to type svm: press tab tab

class Program
{
    svm
}

Result

class Program
{
    static void Main(string[] args)
    {

    }
}

The svm snippet is the same as the sim snippet except it returns no value. Sim returns an integer value. Neither of these snippets have been useful to me, but they are part of Visual Studio and thus necessary for complete coverage.

Switch

Next, we use the switch snippet.
To start,
type switch
and then press tab twice. The "switch_on" identifier is selected. You need to change this to a valid variable. After this, you can add cases to the switch statement.

Case Example
Where to use switch snippet: press tab tab

class Program
{
    static void Main(string[] args)
    {
	switch
    }
}

Result

class Program
{
    static void Main(string[] args)
    {
	switch (switch_on)
	{
	    default:
		break;
	}
    }
}

Result with new switch selection statement

class Program
{
    static void Main(string[] args)
    {
	switch (args.Length)
	{
	    default:
		break;
	}
    }
}
Switch

The switch statement is not popular with developers. More complex problems can often be expressed better with inheritance and virtual methods (object-orientation). And programmers rarely use switch so often that a snippet is necessary.

Object-Oriented ProgrammingVirtual

The switch snippet is not highly useful for many developers, and was probably included in Visual Studio for completeness not actual utility. However, it is nice to know it exists.

Using

Using keyword

Here we show how and where to use the using snippet. Simply type 'using' and then press tab twice. The term 'using' will be expanded into the using-statement. You will want to specify the resource.

Tip:Typically a using statement has a constructor for an object in the resource acquisition part.

Where to put using snippet: press tab tab

class Program
{
    static void Main()
    {
	using
    }
}

Result

class Program
{
    static void Main()
    {
	using (resource)
	{

	}
    }
}
Note

Using statements. Some of the most popular types that are instantiated in using-statements include StreamReader and StreamWriter. You can create your own types with the IDisposable interface.

Using StreamReaderUsing StreamWriter

For quickly inserting a using statement in your C# program, the using snippet is unparalleled. You must change the 'resource' part of the inserted code. Often you will use a Stream-derived type in this context.

Summary

The C# programming language

Snippets are useful if you have to type a huge amount of code. Once you memorize them you no longer will have to type certain constructs. Many developers do not type enough code to really need snippets.

And:Most of the time, a clear understanding of code is more important. Bad code is often worse than useless.


C#: .NET: VS