Namespace
A namespace is an organization construct. It helps us find and understand how a code base is arranged. Namespaces are not essential for C# programs.
But if you encounter an "Are You Missing a Using Directive" error, a namespace may be involved. A simple fix is possible.
This example has namespaces with the identifiers A, B, C, D, E, and F. Namespaces B and C are nested inside namespace A. Namespaces D, E, and F are all at the top level.
Main
entry point has "using" statements for the CClass
, DClass
, and FClass
types.A.B.C
and using D directives are present in namespace E, the Main
method can directly use those types.FClass
, the namespace must be specified explicitly because F is not included inside of E with a using directive.using System; using A.B.C; namespace E { using D; class Program { static void Main() { // Can access CClass type directly from A.B.C. CClass var1 = new CClass(); // Can access DClass type from D. DClass var2 = new DClass(); // Must explicitly specify F namespace. F.FClass var3 = new F.FClass(); // Display types. Console.WriteLine(var1); Console.WriteLine(var2); Console.WriteLine(var3); } } } namespace A { namespace B { namespace C { public class CClass { } } } } namespace D { public class DClass { } } namespace F { public class FClass { } }A.B.C.CClass D.DClass F.FClass
Suppose we have a file, and we want to place its entire contents in a namespace. This would indent every line with a namespace block.
Test.cs
here, the entire file is placed in a namespace. No indentation is required.// Program.cs using System; class Program { static void Main() { Test.TestClass.Print(); } }// Test.cs namespace Test; static class TestClass { public static void Print() { System.Console.WriteLine("OK"); } }OK
Every C# programmer will have encountered this error at some point. The compiler says "Are You Missing a Using Directive."
Find
a squiggly red line in Visual Studio under a type name. Then try to find its namespace—add that (like Test).// using Test; class Program { static void Main() { // We need to have a using statement "using Test" to compile. Option option = new Option(); } } namespace Test { class Option { public int value; } }Error CS0246 The type or namespace name 'Option' could not be found (are you missing a using directive or an assembly reference?)
In addition to using the normal alphanumeric names for namespaces, you can include a period in a namespace. This is a condensed version of having nested namespaces.
There is no performance impact with a namespace. Namespaces do not add complexity to the code itself, just to how it is organized in the source files.
Conceptually, namespaces are an organizational construct. And they provide details about code ownership. They have no effect on memory usage or runtime performance.