← Back to C# Course | Chapter 1: Setup & Basics | Lesson 6 of 7

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:

  1. Namespaces
Syntax
csharp
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

markup
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));
        }
    }
}
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
  1. Forgetting the using System; directive and then writing Console without the namespace (unless implicit usings are enabled).
  2. Using a class from another namespace without a using or the full name, causing a 'type or namespace not found' error.
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.