C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Program: In the Program class, notice how the Main entry point uses the CClass, DClass, and FClass types.
ClassAnd: Because the using A.B.C and using D directives are present in namespace E, the Main method can directly use those types.
Also: With FClass, the namespace must be specified explicitly because F is not included inside of E with a using directive.
C# program that demonstrates namespace use
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 explicitely 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
{
}
}
Output
A.B.C.CClass
D.DClass
F.FClass
Tip: You usually are missing a "using directive." But figuring out the right one to add is not always easy.
Note: Find a squiggly red line in Visual Studio under a type name. Then try to find its namespace—add that (like Test).
C# program that causes compile-time error
// 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;
}
}
Output
Error CS0246
The type or namespace name 'Option' could not be found
(are you missing a using directive or an assembly reference?)
So: At the level of the intermediate language, the namespaces add no computational burden.
However: Namespaces will increase the size of the executable file and the metadata. This is not usually worth considering.