Namespaces help organize code into groups to avoid name conflicts. Using directives let you use code from these groups easily without writing full names.
0
0
Namespaces and using directives in C Sharp (C#)
Introduction
When you want to organize your classes and methods into logical groups.
When you use code from other libraries or parts of your program.
When you want to avoid writing long names for classes by using shortcuts.
When you want to prevent name clashes between classes with the same name.
When you want to keep your code clean and easy to read.
Syntax
C Sharp (C#)
namespace NamespaceName {
// code here
}
using NamespaceName;
// Now you can use classes from NamespaceName without full namesA namespace groups related code under a name.
A using directive lets you use that code without typing the full namespace every time.
Examples
This creates a namespace called
Animals with a class Dog.C Sharp (C#)
using System; namespace Animals { class Dog { public void Bark() { Console.WriteLine("Woof!"); } } }
The
using Animals; lets you create a Dog without writing Animals.Dog.C Sharp (C#)
using System; using Animals; class Program { static void Main() { Dog myDog = new Dog(); myDog.Bark(); } }
You can split one namespace into multiple parts in different places.
C Sharp (C#)
namespace Vehicles {
class Car {}
}
namespace Vehicles {
class Bike {}
}Sample Program
This program defines a Hello class inside the Greetings namespace. In Main, it creates an object of Hello using the full namespace name and calls its method.
C Sharp (C#)
using System; namespace Greetings { class Hello { public void SayHello() { Console.WriteLine("Hello from Greetings namespace!"); } } } class Program { static void Main() { Greetings.Hello greet = new Greetings.Hello(); greet.SayHello(); } }
OutputSuccess
Important Notes
You can use multiple using directives at the top of your file.
If two namespaces have classes with the same name, you can use the full name to avoid confusion.
Namespaces help keep your code organized and easier to maintain.
Summary
Namespaces group related code to avoid name conflicts.
Using directives let you use code from namespaces without typing full names.
They make your code cleaner and easier to read.