C# Namespace


What is a namespace? Namespaces are the .NET way of providing containers for application code, such that the code and its contents can be uniquely identified. Namespaces are also used as a means of categorizing items in the .NET Framework.

A namespace is a domain within which type names must be unique. Types are typically organized into hierarchical namespaces—both to avoid naming conflicts and to make type names easier to find.

Namespaces are independent of assemblies, which are units of deployment such as an .exe or .dll. Namespaces also have no impact on member accessibility—public, internal, private, and so on.

C# code by default is contained in the global namespace. Items contained in this code are accessible from other code in the global namespace simply by referring to them by name. You can use the namespace keyword to explicitly define the namespace for a block of code enclosed in curly braces ({}).

Names in a namespace must be qualified if they are used from code outside of this namespace. A qualified name is one that contains all of its hierarchical information. This means that if you have code in one namespace that needs to use code in a different namespace, you must include a reference to this namespace.

The using directive imports a namespace and is a convenient way to refer to types without their fully qualified names.

The using statement doesn’t in itself give you access to names in another namespace. Unless the code in a namespace is somehow linked to your project, by being defined in a source file in the project or being defined in some other code linked to the project, you won’t have access to the names contained. using simply makes it easier to access the names and can shorten lengthy code and make it more readable.

A namespace is declared for your application code. The name used is the one you supplied when you created your project. using static System.Console allows you to simply use WriteLine() instead of Console.WriteLine() in a console application. You can use a code snippet however to save yourself the typing in this case. The snippet is cw.

Mosh Hamedani briefly discusses namespaces in his C# series of 3 Udemy courses. Look into the Beginner course and look at the video 28 Demo: Classes. You can create a new folder in your project to store your files that contain classes, but if you do you will have to update your namespace. If your new folder is called “Math”, your project is called “MyProject”, and you class file in the “Math” folder is called “Calculator.cs”, then you need to qualify the namespace inside your Calculator.cs file. To create the Math folder, right-click the project in Solution Explorer and choose new Folder. Below is what the Calculator.cs file would look like.

namespace MyProject.Math
{
   class Calculator
   {
   }
}