Share via


Visual Studio Tip #5: Quickly adding a namespace “using” statement

One thing that slows down new C# users is the requirement to add “using” statements to the top of your file. This is because they just want to declare a variable and use it but aren't necessarily familiar enough with the classes and namespaces to have predicted the need for the namespace when they were at the top of the file. So they end of hundreds of lines into a file and realize that the class they need to use requires a using statement all-the-way-at-the-top.

There are a couple of ways to add a using directive to your file to include the namespace. The obvious way is to scroll all the way to the top of your file and type it in. But that’s also the slowest and most error prone and takes you away from the line of code you are working on. The quickest way is just two key strokes and doesn’t move your cursor.

Imagine we want to write this method

image

The WebClient class is in the System.Net namespace which is not one of the ones usually included in a newly created file. So when you start to use it you get red squigglies because you need to put “using System.Net;” at the top of the file

image

But don’t scroll all the way up there. Instead, when you finish typing the class name, keep your cursor on the word WebClient (or right at the end). Then press the Control key and the Period key   (Ctrl + ‘.’ )

This will reveal the Resolve menu

image

The first item is highlighted and says “using System.Net;” so press Enter to accept that. Visual Studio will put that using statement at the top of your file with the others. You will know that it is there because the WebClient text will change color to indicate it is a now recognized type.

image

then just continue typing in the rest of your code.

image

There are other ways to do this such as right clicking on the word WebClient and looking for “Resolve” in the context menu but I find that the simple keystrokes of Ctrl+ ‘.’ and Enter are quick and efficient because my cursor never moves, which would interrupt my code writing flow. This will work for any symbol that your cursor is on – as long as the assembly for the type is already added to your references.

(next tip: turn on line numbers - with Quick Launch!)

This post is part of a series of Visual Studio tips. The first post in the series contains the whole list.