Member-only story

Namespace in C# with Example

Shahzad Aslam
2 min readApr 27, 2024

--

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.

Namspace in C# with Example

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…

--

--

Shahzad Aslam
Shahzad Aslam

Written by Shahzad Aslam

Welcome to c-sharptutorial.com. I am Shahzad Aslam. I am the founder of c-sharptutorial.com. I'm currently living near Islamabad, Pakistan.

Responses (1)