Visual C# Built In Code Snippets For Fast Productivity

Code snippets are ready made, which means they are really useful reusable codes which need to be used and then again used at someother  part of work.

These snippets are not really of the type which are only used by just placing a cursor and inserting it to the place you want, but some are surrounded with code snippets also in which some line of code has been selected and then surrounded with required if statement, for loop and so on.

Code Snippets have following Advantages:

  • It saves a lot of your time by saving reusable code in code snippet manager and you can later use it anywhere.
  • It increases productivity by simply inserting code in you desired location.
  • It reduces the chances of less error by re typing your line of code.
  • It helps to stream line your work as per you assigned deadline.

Code Snippet Manager:

Firstly, you can check a whole list of code snippets in code snippets manager which you can open by pressing Combination of (Ctrl + K, Ctrl + B).


You can alternatively open code snippet manager from Visual Studio Menu from Tools è Code Snippets Manager...


There is another way to open as introduced in latest versions of visual studio which is very beneficial to open the menu items in less time; it is the Quick Launch Search Box Displayed in Top Right of your Visual Studio IDE.

As you type text it gives you suggestions and suggestions to do more actions also, like it displays the most Recently used items and Nuget Package Manager search for the searched keyword.


How to Use Code Snippets:

Basically there are two types of code snippets to be used; First one is by placing cursor at location and typing some code snippet code and secondly by using surround-with code snippets.

Note: At any time if you do not want to select the desired code snippets Press ESC Button it will dissolve and does not insert the code snippet.

Cursor Based Code Snippets:

Usage of code snippets is very simple. Just place cursor at the desired location where you want to insert code snippets, type snippet code and Press TAB Button Twice to insert in the place… we will discuss full list of code snippets in this article after following this but for reference I am quoting here an example of code snippet… for example you want to add for loop, just write for and press twice to check the magic of code snippet inserting and with full syntax and with default values. It Increases your productivity and time by also reducing the risk of human errors while creating complex syntax like for loop.

You can use it from Keyboard shortcut also by pressing key combination of (Ctrl + K, Ctrl + X) and select the Visual C# Category.


But if you have to remember the snippet code you can type it.


Surround-With Code Snippets:

You can use surround with code snippets by selecting the line of code and press keyboard short cut key combination (Ctrl + K, Ctrl + S) and type the desired code snippet to wrap in the line of code.


List of Available Code Snippets:

Now we will move into the using of code snippets inside IDE.

#region:

Region directive is used to define certain region in the code which specifies certain functionality or scope of certain work. It is collapsible portion and it is useful for pages which has lengthy code written so that you can collapse the region of code and focus on your work.

The start #region must be terminated with #endregion directive otherwise it will through the exception.

#region has a scope of anywhere means you can insert it anywhere you want.


(~):

This code snippet has scope only in class as class has destructors.


As already mentioned that has scope with in class so I checked it with creating outside the scope of class, although it created as it is snippet but it will generate compile error or a namespace cannot directly contain members such as fields or methods, while the other one inside the class scope did not through any exception.

ctor:

This code snippet is used to create constructor of a class. It has also scope within class otherwise it generate exception.

Type ctor and press TAB twice to insert.


class:

This snippet will create a declaration of class. It has a scope of namespace (global), class or struct.

enum:

This is used to declare enumeration. This is used to build a list of distinct enumerators. It has a scope of inside namespace, class or struct. The default value for initial first enumerator is 0 and the successive items will follow it like 0, 1 and so on. Enums cannot contain whitespaces while declaring their names.

The approved types of enum are int, long, byte,unit,ulong,ushort,short and sbyte.


cw:

Very helpful snippet cw means Console.WriteLine() which can show current line terminator to the output stream. Its scope lies inside method, indexer, property or event accessor.

It can take string as a parameter and return to output stream. You can align string to New Line also by using Console.Out.NewLine, 

  1. Console.WriteLine();  

equals:

The Equals as the name defined it has behavior to check equal of two objects either they are of same type or of different type and it returns Boolean value, if matched it return true otherwise false.

Its scope lies only inside class or struct.

  1. // override object.Equals  
  2.   
  3. public override bool Equals(object obj)  
  4.   
  5. {  
  6.   
  7. //  
  8.   
  9. // See the full list of guidelines at  
  10.   
  11. // http://go.microsoft.com/fwlink/?LinkID=85237  
  12.   
  13. // and also the guidance for operator== at  
  14.   
  15. // http://go.microsoft.com/fwlink/?LinkId=85238  
  16.   
  17. //  
  18.   
  19. if (obj == null || GetType() != obj.GetType())  
  20.   
  21. {  
  22.   
  23. return false;  
  24.   
  25. }  
  26.   
  27. // TODO: write your implementation of Equals() here  
  28.   
  29. throw new NotImplementedException();  
  30.   
  31. return base.Equals(obj);  
  32.   
  33. }  
  34.   
  35. // override object.GetHashCode  
  36.   
  37. public override int GetHashCode()  
  38.   
  39. {  
  40.   
  41. // TODO: write your implementation of GetHashCode() here  
  42.   
  43. throw new NotImplementedException();  
  44.   
  45. return base.GetHashCode();  
  46.   
  47. }  

exception:

Creates a declaration for class that derives from exception by default. Exceptions are errors which are generated by the application. Its scope is inside a namespace, class or struct. 

  1. [Serializable]  
  2.   
  3. public class MyException : Exception  
  4.   
  5. {  
  6.   
  7. public MyException() { }  
  8.   
  9. public MyException(string message) : base(message) { }  
  10.   
  11. public MyException(string message, Exception inner) : base(message, inner) { }  
  12.   
  13. protected MyException(  
  14.   
  15. System.Runtime.Serialization.SerializationInfo info,  
  16.   
  17. System.Runtime.Serialization.StreamingContext context)  
  18.   
  19. base(info, context) { }  
  20.   
  21. }  

for:

for statement is most probably used to run together block of statements in a repeated fashion until you statements return false. The best possible scenario for using for loop having you know number of iterations required to get possible operation.

  1. for (int i = 0; i < length; i++)  
  2.   
  3. {  
  4.   
  5. }  
foreach:
 
foreach iterates through for each element in an array or object collection that implements IEnumerable or Generic IEnumerable Interface.
It just iterate to the collection of items but it does not for adding or removing items. you can use break and continue operation inside foreach loop as per your easness.
  1. foreach (var item in collection)    
  2.         {    
  3.                 
  4.         }   
for:
 
this code snippet is for decrementing values  after each iteration using for loop. Its scope is as same as for loop.
  1. for (int i = length - 1; i >= 0; i--)  
  2.        {  
  3.              
  4.        }  
if:

it is the most important and too many used code snippet in daily work routine. due to its  simplicity its as important as you think you have to include for every block statement to check for. It has scope inside a method, indexer, property or event accessor. by default it has true value like we are checking for check box which is either checked or not so that we can evaluate the if ... else condition on the base of it.
  1. if (true)  
  2.         {  
  3.               
  4.         }  
Interface:

by inserting this snippet it create the interface declaration. an interface only contain the signature of methods, indexer,events pr properties. a class which implements the interface must used the members which interface has defined.  An Interface can inherit from one or more base classes. it has scope inside a class, struct or namespace (global).
  1. interface IInterface  
  2. {  
  3.       
  4. }  
namespace:

it declare a scope / set of related objects. inside a namespace you can declare one or more namespace,c lass, struct, enum, interface and delegate.

it has scope only inside namespace which has global scope.
  1. namespace MyNamespace  
  2. {  
  3.        
  4. }  
prop: it created auto-implemented property inside a class or struct.you can initialize certain properties with some initial value.
  1. public int MyProperty { getset; }  
propfull: it can create property declaration with get  and accessors and it has scope only inside a class or struct.
  1. private int myVar;  
  2.   
  3.     public int MyProperty  
  4.     {  
  5.         get { return myVar;}  
  6.         set { myVar = value;}  
  7.     }  
switch:

It is a control statement which selects a switch section and break no succeeding section should be checked. each switch section contains one or more case labels followed by one or more statements depending on the scenario. 
  1. switch (switch_on)  
  2.         {  
  3.             default:  
  4.         }  
try: 

create a try....catch block. the most important purpose of try ... catch is to catch unhandled exceptions by trying a block of code and it successful it moved to the next section or move out of the method block and if not successful it go to the catch section where customized as well as other exception are thrown to identify the type of breakage caused by the try code.
  1. try  
  2.        {  
  3.   
  4.        }  
  5.        catch (Exception)  
  6.        {  
  7.              
  8.            throw;  
  9.        }  
tryf: the basic purpose of using finally with try block is to cleanup the resources which is occupied by try block, 
  1. try  
  2.         {  
  3.   
  4.         }  
  5.         finally  
  6.         {  
  7.   
  8.         }  
while:

It executes block of statements until the expression is not set to false. The executing statement can also be terminated by adding break, go to like statements. It has scope inside a  method, indexer, property or event accessor.  
  1. while (true)  
  2.        {  
  3.              
  4.        }  
That's all about some of the useful code snippets but there are some others; you can check full code snippets  manager for full list.
 
Read more articles on Visual Studio:

Up Next
    Ebook Download
    View all
    Learn
    View all