Namespaces
A namespace is like a last name that keeps two people called Sam apart. It groups related pieces of code so names do not clash when many people write code together.
In this page:
Syntax
namespace Company.Project
{
class ClassName { }
}
using Company.Project; // import to use short names
Namespaces
Namespaces group related classes together and prevent naming collisions between libraries. You declare your own namespace with the namespace keyword, and pull in others with using. Large C# codebases rely heavily on namespaces to stay organized.
Note:
Namespace names conventionally follow a dotted, PascalCase pattern like
Company.Product.Module.Example: Namespaces
using System;
namespace MyApp.Utilities
{
class MathHelper
{
public static int Square(int n) => n * n;
}
}
namespace MyApp
{
using MyApp.Utilities;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(MathHelper.Square(5));
}
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting the
using System;directive and then writingConsolewithout the namespace (unless implicit usings are enabled). - Using a class from another namespace without a
usingor the full name, causing a 'type or namespace not found' error. - Giving two different types the same name in the same namespace, which is a compile error.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: