Member-only story
Namespace in C# with Example
A namespace is a container of group related classes, structs, enums, interfaces, and other types. You can organize related classes in a specific namespace. Namespaces help avoid naming conflicts between types and provide a hierarchical structure for organizing your code.

The below is syntax of declaring and use of namespace:
We use namespace keyword then give the name of namespace to writing a namespace.
Syntax of Namespace
namespace FruitNamespace
{
// Types and members go here
}
Example
namespace FruitLibrary
{
public class MangoUtils
{
public void GetFruitColor(string color)
{
return color;
}
}
public class GraspeUtils
{
public void GetFruitColor(string color)
{
return color;
}
}
}
Using Directives:
To use types from a namespace in your code, you can add a using directive at the top of your C# file. This allows you to reference types from the namespace without specifying the full namespace each time.
Example
using FruitLibrary
class Program
{
static void Main()
{
string result = MangoUtils.GetFruitColor("Yellow"); // Using MangoUtils from FruitLibrary
Console.WriteLine(result)
}
}
Nested Namespaces:
You can define a namespace within a another namespace and can create a hierarchical structure. This is useful for further organizing your code.
Example
namespace FruitApplication
{
namespace MangoApplication
{
public class GreenMango
{
public void GetFruitColor(string color)
{
return color;
}
}
}
}
To use types from nested namespaces, you can either use the full namespace path or include multiple using directives:
using FruitApplication.MangoApplication;
class Program
{
static void Main()
{
string result = GreenMango.GetFruitColor("Green"); // Using MangoUtils from FruitLibrary
Console.WriteLine(result)
}
}