C#

6 Of My Favorite Visual Studio Shortcuts

Trusted By

Welcome Back! I hope you enjoy the content on this site. If you have not done so already, you may want to subscribe to my RSS feed or become a fan of this blog on Facebook. Thanks for visiting!

These are some of my favorite and most used shortcuts in visual studio:

  1. Ctrl + - and the opposite Ctrl + Shift + -  To move the cursor back or forward to the last position without having to scroll or switch  files.
  2. Shift+Alt+Enter Switches to Full Screen Mode
  3. Ctrl+K, Ctrl+C Comment a block,   Ctrl+K, Ctrl+U Uncomment the block
  4. Shift + Alt + F10 then Enter expands the smart tag to insert a using statement or implement an Interface
  5. Ctrl+K, Ctrl+D Auto format the file (Source, xml or  html)
  6. Ctrl+M, Ctrl+ O Collapses all outlining to  definition and then Ctrl+M, Ctrl+M to toggle the current block to expanded or collapsed.

What about you what are your favorites. I would like this post to become a repository for the most used Visual Studio Shortcuts. So do share

Hope This Helps!

Hatim

10 Not So Well Known Keywords in C#

Ok before the flaming start let me state this. These are known to most hardcore programmers and not knowing them doesn’t make you less of a programmer either.

That said these keywords can come in handy and allow for better code quality and readability. Enjoy!

yield

The yield keyword signals to the compiler that the method in which it appears is an iterator block. The compiler generates a class to implement the behavior that is expressed in the iterator block. In the iterator block, the yield keyword is used together with the return keyword to provide a value to the enumerator object. This is the value that is returned, for example, in each loop of a foreach statement. The yield keyword is also used with break to signal the end of iteration.

example:

  public classList
 
{
       //using System.Collections;
     
public static IEnumerable Power(int number, int exponent)
       {
           int counter = 0;
           int result = 1;
           while(counter++ < exponent)
           {
               result = result * number;
               yield returnresult;
           }
       }

       static void Main()
       {
           // Display powers of 2 up to the exponent 8:
         
foreach (int i inPower(2, 8))
           {
               Console.Write("{0} ", i);
           }
       }
   }
   /*
   Output:
   2 4 8 16 32 64 128 256
   */

msdn reference: http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx

var

Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.

An application running on version 2.0 can also use the var keyword in their code as long as it’s compiled with 3.0 or up and set to output to 2.0.

example:

var i = 10; // implicitly typed

int i = 10; //explicitly typed

msdn reference: http://msdn.microsoft.com/en-us/library/bb383973.aspx

using()

Defines a scope, outside of which an object or objects will be disposed.

example:

using (C c = new C())

{

    c.UseLimitedResource();

}

msdn reference: http://msdn.microsoft.com/en-us/library/yh598w02%28VS.80%29.aspx

readonly

The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.

msdn reference: http://msdn.microsoft.com/en-us/library/acdd6hb7%28VS.80%29.aspx

as

The as operator is like a cast operation. However, if the conversion is not possible, as returns null instead of raising an exception. 

example:

class Base

   
{ public override string ToString()

        {

            return "Base";

        }

    }

    class Derived : Base

   
{ }

    class Program

   
{

        static void Main()

        {

            Derived d = new Derived();

            Base b = d as Base;

            if (b != null)

            {

                Console.WriteLine(b.ToString());

            }

        }

    }

msdn reference: http://msdn.microsoft.com/en-us/library/cscsdfbt.aspx

is

Checks if an object is compatible with a given type.

An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.

The is keyword causes a compile-time warning if the expression is known to always be true or to always be false, but typically evaluates type compatibility at run time.

The is operator cannot be overloaded.

example:

class Class1{ }

classClass2{ }

classClass3: Class2{ }

classIsTest

  
{

        static voidTest(objecto)

        {

            Class1a;

            Class2b;

            if(o isClass1)

            {

                Console.WriteLine("o is Class1");

                a = (Class1)o;

                // Do something with "a."

           
}

            else if (o is Class2)

            {

                Console.WriteLine("o is Class2");

                b = (Class2)o;

                // Do something with "b."

           
}

            else

           
{

                Console.WriteLine("o is neither Class1 nor Class2.");

            }

        }

        static void Main()

        {

            Class1 c1 = new Class1();

            Class2 c2 = new Class2();

            Class3 c3 = new Class3();

            Test(c1);

            Test(c2);

            Test(c3);

            Test("a string");

        }

    }

    /*

    Output:

    o is Class1

    o is Class2

    o is Class2

    o is neither Class1 nor Class2.

    */

msdn reference: http://msdn.microsoft.com/en-us/library/scekt9xw.aspx

default

    n generic classes and methods, one issue that arises is how to assign a default value to a parameterized type T when you do not know the following in advance:

    • Whether T will be a reference type or a value type.

    • If T is a value type, whether it will be a numeric value or a struct.

    Given a variable t of a parameterized type T, the statement t = null is only valid if T is a reference type and t = 0 will only work for numeric value types but not for structs. The solution is to use the default keyword, which will return null for reference types and zero for numeric value types. For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types. For nullable value types, default returns a System.Nullabe<T>, which is initialized like any struct.

    example:

    T temp = default(T);

    msdn reference: http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx

    global

    The global contextual keyword, when it comes before the :: operator, refers to the global namespace, which is the default namespace for any C# program and is otherwise unnamed.

    example:

    class TestClass : global::TestApp { }

    msdn reference: http://msdn.microsoft.com/en-us/library/cc713620.aspx

    volatile

    The volatile keyword indicates that a field might be modified by multiple concurrently executing threads. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times.

    msdn reference: http://msdn.microsoft.com/en-us/library/x13ttww7%28VS.80%29.aspx

    extern alias

    It can sometimes be necessary to reference two versions of assemblies that have the same fully-qualified type names, for example when you need to use two or more versions of an assembly in the same application. By using an external assembly alias, the namespaces from each assembly can be wrapped inside root-level namespaces named by the alias, allowing them to be used in the same file.

    To reference two assemblies with the same fully-qualified type names, an alias must be specified on the command line, as follows:

    /r:GridV1=grid.dll

    /r:GridV2=grid20.dll

    This creates the external aliases GridV1 and GridV2. To use these aliases from within a program, reference them using the extern keyword. For example:

    extern alias GridV1;

    extern alias GridV2;

    Each extern alias declaration introduces an additional root-level namespace that parallels (but does not lie within) the global namespace. Thus types from each assembly can be referred to without ambiguity using their fully qualified name, rooted in the appropriate namespace-alias

    In the above example, GridV1::Grid would be the grid control from grid.dll, and GridV2::Grid would be the grid control from grid20.dll.

    msdn reference: http://msdn.microsoft.com/en-us/library/ms173212%28VS.80%29.aspx

     

    Hope this helps!

    Hatim

    5 Useful Visual Studio C# Snippets – Part 2

    I 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 I hope would be as helpful as the first one.

    Reading an embedded resource as a stream

    Specially when sending patches to customers, sometimes I need to embed an XML file that would contain some data that needs to be imported to the database in a compiled exe or dll to simplify the process for them. So I ended up creating a snippet on how to read an embedded resource

    Shortcut: rembed

    Sample Result:

    Stream rulesReader = typeof(MyObject).Assembly.GetManifestResourceStream(
              typeof(MyObject), "Resources.AttestationContratWorkflow.rules");

     

    Customization:

    • The type of the object to get the assembly from
    • The name of the embedded resource
    ViewState property

    Even though I avoid using  the viewstate as much as I can to keep the size of the page small but sometimes you really need to.

    Shortcut: vstate

    Sample Result:

    public string Title
    {
        get
        {
            if (ViewState["Title"] == null)
                return "My Title";
    
            return (string)ViewState["Title"];
        }
        set
        {
            ViewState["Title"] = value;
        }
    }

     

    Customization:

    • The type of the property
    • The name of the property
    • The default return value
    Null argument validation

    I would say this is one of the basic best practices to have and to stick to. My Eiffel professor would be so proud of me :)

    Shortcut: nparam

    Sample Result:

    if (context == null)
    {
       throw new ArgumentNullException("context ");
    }

     

    Customization:

    • The name of the parameter
    Info Message Box

    This snippets shows an Information Message box.

    Shortcut: ibox

    Sample Result:

    MessageBox.Show(this, "My Information Message", "Information...", MessageBoxButtons.OK,

                     MessageBoxIcon.Information);

    Customization:

    • The message
    Error Message Box

    Same as the previous snippet but shows an error message instead

    Shortcut: ebox

    Sample Result:

    MessageBox.Show(this, "My Error Message", "Error...", MessageBoxButtons.OK, 

                     MessageBoxIcon.Error);

    Customization:

    • The message

     

    Download the snippets

    Hope  this helps!

    Hatim

    Digg This

    5 Useful Visual Studio C# Snippets

    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.

    image

    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

     

    Download the snippets.

    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

    Digg This