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:
AliceWithout 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
MediumYou 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.
Cheat sheet
Namespaces organize code and prevent naming conflicts by grouping related classes together.
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);
}
}Without a using directive, use the fully qualified name:
MyApp.Models.User user = new MyApp.Models.User("Bob");The System namespace contains fundamental classes like Console.
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
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesNamespaces & DirectivesIntro to Classes & ObjectsThe 'this' KeywordMethods and ParametersFields vs PropertiesConstructorsObject InitializersRecap - Simple Calculator4Inheritance
Basic Inheritance (:) SyntaxThe 'base' KeywordVirtual & Override KeywordsSealed ClassesThe 'object' Base ClassRecap - Employee Hierarchy7Advanced Features
Operator OverloadingIndexers (this[])ToString() OverrideExtension MethodsRecap - Custom List2Properties & Static Members
Auto-Implemented PropertiesRead/Write-Only PropertiesStatic Fields & MethodsStatic ClassesExpression-Bodied Members5Polymorphism & Interfaces
Compile vs Runtime PolyInterface vs Abstract ClassMultiple InterfacesExplicit InterfacesUpcasting & DowncastingRecap - Shape Calculator