Menu
Coddy logo textTech

Namespaces & Directives

Part of the Object Oriented Programming section of Coddy's C# journey — lesson 2 of 70.

Namespaces organize your code and prevent naming conflicts. They group related classes together like folders organize files.

Create a class inside a namespace

namespace MyApp.Models
{
    public class User
    {
        public string Name { get; set; }
        
        public User(string name)
        {
            Name = name;
        }
    }
}

Use a using directive to access classes from another namespace

using System;
using MyApp.Models;

class Program
{
    static void Main()
    {
        User user = new User("Alice");
        Console.WriteLine(user.Name);
    }
}

Output:

Alice

Without a using directive, you must use the fully qualified name

MyApp.Models.User user = new MyApp.Models.User("Bob");

The using directive allows you to reference types in a namespace without typing the full namespace path each time. System is a common namespace containing fundamental classes like Console.

challenge icon

Challenge

Medium

You have a User class in the MyApp.Models namespace. Add the correct using directive in Program.cs to use the User class without the fully qualified name.

Try it yourself

using System;
// TODO: Add using directive for MyApp.Models

class Program
{
    static void Main()
    {
        string userName = Console.ReadLine();
        // TODO: Create a User object using userName
        // TODO: Print "User created: " followed by the user's Name
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming