Monday, July 27, 2009

Automatically Find the Namespace of a Class and Add a Using Statement in Visual Studio

This is an all-too-common question on the forums for me not to address it here. This post concerns a very basic C# concept.

Sometimes, when adding a code snippet, it's possible you might get an error that says something to the effect of "The name "xxx" does not exist in the current context".

At compile time, a namespace reference must be found in order to resolve classes that will be used within an application. Classes can be resolved to their namespaces either with the using directive, or by using the fully qualified class name when referring to a class.

Employing the using directive would look like this:


using System;
using System.Reflection;

namespace MyNamespace
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine(Assembly.GetExecutingAssembly().GetName().Version);
}
}
}


While employing a fully qualified namespace reference would look like this:


namespace MyNamespace
{
public class Program
{
public static void Main(string[] args)
{
System.Console.WriteLine(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
}
}
}


Typically, the using directive is preferred, as it usually creates cleaner, and easier to read code, but sometimes the fully qualified class name makes more sense, especially when two or more namespaces contain different classes with the same name.

If both of these above constructs are missing from the code file, the error described above will be the result.

Most of the time, this situation can be done by following the following simple steps:

1. Place the text caret in the middle of the class name that is causing the error. Alternatively, you can simply double click on the error in the Errors window.

2. Press Shift+Alt+F10. If the class can be found, a set of options will appear to add the namespace reference to the class. The options that start with "using" will add the using directive to the top of the code file, while the options that simply have the namespace name will change the class reference in code to use the fully qualified class name.

Occasionally, however, it's necessary to add a reference to the assembly containing the class. You can do this by right clicking the "References" folder within the project, and selecting "Add Reference....". Select the applicable tab:

.NET - For .NET Assemblies located in the GAC.

COM - For older COM assemblies registered in the system.

Projects - For references to projects that reside within the same solution as the current project.

Browse - To browse the file system for a specific file.

Recent - For references that have recently been added.

Finally, select the assembly you need to reference, and click OK.

After a reference has been added, you can go back to step 1 above, and ensure the using directive or the fully qualified class name results in the proper resolution of the class.