5 Useful Visual Studio C# Snippets
- 12
- Add a Comment
If you're new here, you may want to subscribe to my RSS feed or become a fan of this blog on Facebook. Thanks for visiting!
When working on a given project I always create Visual Studio snippets for repetitive tasks to save time and avoid mistakes. Of course each project has some specific requirements and therefore it’s not always the same code that is repeated.
The best snippets are the ones you would create yourself. But here are a few that I find are pretty generic and saved me sometime and hope you will find useful as well.
EventHandler
This snippet will create a generic event handler method. It’s pretty useful when working with ASP.Net controls and you don’t like to switch to the design view to then double click or go into properties of an element to generate the event handler by fear that the designer would mess something up.

Shortcut: evh
Sample Result:
void btnSubmit_Click(object sender, EventArgs e) { }
Customization:
- The name of the method
- The EventArgs type
OnEvent
This one is a no brainer, so I use it to save time and avoid forgetting to check if the event is null before raising it.
Shortcut: onevt
Sample Result:
protected void OnEvent(EventArgs args) { if (myEvent != null) { myEvent(this, args); } }
Customization:
- The name of the method
- The EventArgs type
- The Event to raise
Singleton Class
We all need a singleton class at one point or another in most of our projects. I think it’s the most used software pattern and so it deservers it’s own snippet. Oh, it’s thread safe
The implementation used is available here:
http://msdn.microsoft.com/en-us/library/ms998558.aspx
Shortcut: snglt
Sample Result:
using System; public sealed class Singleton { private static volatile Singleton instance; private static object syncRoot = new Object(); private Singleton() {} public static Singleton Instance { get { if (instance == null) { lock (syncRoot) { if (instance == null) instance = new Singleton(); } } return instance; } } }
Customization:
- The class name
SqlDataReader with Stored Procedure
We generate most of our Data Access code but for custom business requirements we end up creating specific stored procedures. So instead of copy/paste from another file I have created this snippet.
Shortcut: sqlproc
Sample Result:
using (SqlConnection sqlConnection = new SqlConnection(myConnectionString)) { using (SqlCommand sqlCommand = new SqlCommand("myStoredProcedure",sqlConnection)) {
sqlCommand.CommandType = CommandType.StoredProcedure;
#region params
//add your parameters here
#endregion
SqlDataReader dr = null;
try
{
sqlCommand.Connection.Open();
dr = sqlCommand.ExecuteReader();
while (dr.Read())
{
//do your mapping here
}
}
catch (SqlException)
{
//handle exception
}
finally
{
if (dr != null && !dr.IsClosed)
dr.Close();
if (sqlCommand.Connection.State != ConnectionState.Closed)
sqlCommand.Connection.Close();
}
}
}
Customization:
- Connection string
- Stored Procedure name
Serialize/Deserialize an object from an XML string
I can never remember the correct syntax for doing this and I am always looking at an other project to copy/paste this code so I ended up creating a snippet for it too.
Shortcut: serial
Sample Result:
public static List<MenuGroup> Deserialize(string strXml) { XmlSerializer serializer = new XmlSerializer(typeof(List<MenuGroup>)); StringReader reader = new StringReader(strXml); return (List<MenuGroup>)serializer.Deserialize(reader); } public static string Serialize(List<MenuGroup> items) { XmlSerializer serializer = new XmlSerializer(typeof(List<MenuGroup>)); StringBuilder sb = new StringBuilder(); StringWriter writer = new StringWriter(sb); serializer.Serialize(writer, items); return sb.ToString(); }
Customization:
- Type to Serialize
To add this snippets to Visual Studio then Tools –> Code Snippets Manager … select Import… and browse to where you extracted the downloaded file.
Happy coding!
Hatim

12 Comments
Ivan Suhinin
April 16th, 2009
at 6:11am
Nice snippets, though I think the following ones are incorrect:
protected void OnEvent(EventArgs args)
{
if (myEvent != null)
{
myEvent(this, args);
}
}
Should be
protected void OnEvent(EventArgs args)
{
EventHandler local = myEvent;
if (local != null)
{
local(this, args);
}
}
AND
I think singleton with nested private class is much sexier than your example.
http://www.yoda.arachsys.com/csharp/singleton.html
Reflective Perspective - Chris Alcock » The Morning Brew #328
April 16th, 2009
at 7:27am
[...] 5 Useful Visual Studio C# Snippets - Hatim Rih shares 5 useful Visual Studio Snippets which provide implementations of 5 common coding tasks [...]
Rene Schulte
April 16th, 2009
at 8:34am
I prefer a generic base class for the singleton pattern. No copy & paste due to a code snippet.
See http://stackoverflow.com/questions/100081/whats-a-good-threadsafe-singleton-generic-template-pattern-in-c
5 Useful Visual Studio C# Snippets – Part 2 | Hatim's Development Blog
April 16th, 2009
at 11:55am
[...] initially published 5 Visual Studio c# Snippets yesterday and it got a lot of attention and had some positive feedback, so this is a follow up that [...]
Jelle Hissink
April 16th, 2009
at 12:43pm
Thanks for posting.
I just had a few notes in additon to those mentioned by Ivan:
- If you can an using clause around the ExecuteReader:
using (SqlDataReader dr = sqlCommand.ExecuteReader())
- You don’t need to close the connection (Dispose() on the connection will take care of that.
- If you alter the two points above, you can remove the finally block
- Also why do add a place in that code where you process the SqlExceptions, why not put that try-catch block around the entire code, that way you will dispose of the reader, command, and connection before handling the errors.
Valamas
April 16th, 2009
at 10:24pm
Hi,
I cannot see Tools –> Code Snippets Manager in my Visual Studio 2005 / 2008. Can anyone help?
I checked add/remove features of Visual Studio setup to see if it was an option i didn’t select. Not listed there.
cheers,
rw
April 17th, 2009
at 7:37am
protected void OnEvent(..) should be virtual
Compare with this snipplet http://gotcodesnippets.com/1117.snippet
i posted some time ago
todd
April 17th, 2009
at 3:50pm
Your SqlProc shortcut just perpetuates the bad practice of blindly swallowing exceptions. Using this shortcut you don’t have to fill out the exception block so the default case would be to ignore any sql exceptions.
At a minimum it should be modified so that it won’t compile unless you modify the exception block code, better yet remove it.
Hatim
April 17th, 2009
at 7:57pm
Todd,
My snippet included code that would log the exception and handle it correctly, but that’s using custom libraries that we built so I had to remove. For everyone else they should know how to deal with exceptions and add that code to the catch block or even better modify the snippet to have their custom code in it.
These snippets are just helpers and not an end solution, it’s just a shortcut to save messing things up and to have some structure, that’s all!
Visual Studio Links #112 : Visual Studio Hacks
April 21st, 2009
at 6:15pm
[...] Rih posted 5 useful Visual Studio C# snippets. Hatim also followed up with a Part [...]
Roger
May 18th, 2009
at 5:27pm
I might be wrong but I don’t think you have to invoke the close() method on either the datareader or sqlconnection object because they are defined in the using() statement.
The using statement automatically calls dispose after the scope is finished (end curly brace), and I believe that close() is already called if necessary during the dispose, but like I said I could be wrong.
Chris
June 23rd, 2009
at 8:58am
Very usefull!
Thanks for that!