In C#, namespaces play a crucial role in structuring classes. They are essential for managing the scope of methods and classes within a substantial .NET project, enhancing code organization and maintainability. When working with C# programs, the convention is to reference classes like System.Console, where "System" represents the namespace and "Console" signifies the class. To access a class from a specific namespace, the syntax NamespaceName.ClassName is utilized.
In C#, a namespace is declared by utilizing the namespace keyword, then specifying the namespace identifier, and enclosing it within a set of curly braces {} which encapsulate its contents.
Syntax:
It has the following syntax.
namespacename_of_namespace {
// Namespace ( Nested Namespaces )
// Classes
// Interfaces
// Structures
// Delegates
}
Where,
- Namespace nameofnamespace: It declares the name of the namespace.
- Nested Namespace: It specifies the namespace inside another namespace.
- Classes: It represent the blueprint for creating objects.
- Interface: It defines a contract that contains a method signature without implementation.
- Structure: It specifies the light-weighted data type that holds the data.
- Delegates: It is a type that holds a reference to a method safely.
C# Namespace Example
Let's consider an example to demonstrate the concept of namespace in C#.
Example
using System;
namespace Name1 // define a namespace
{
class C1
{
public void Show() =>Console.WriteLine("Hello from Name1");
}
}
namespace Name2 // define a namespace
{
class C2
{
public void Show() =>Console.WriteLine("Hello from Name2");
}
}
class C# Tutorial
{
static void Main()
{
Name1.C1 obj1 = new Name1.C1();
Name2.C2 obj2 = new Name2.C2();
obj1.Show();
obj2.Show();
}
}
Output:
Hello from Name1
Hello from Name2
Explanation:
In this instance, we have utilized two namespaces called Name1 and Name2, each housing a class C1 and C2. Within the main function, we instantiate objects (obj1, obj2) of these classes (Name1, Name2) and invoke the Show method to display the results.
Accessing the Members of a Namespace
In C# coding, the elements of a namespace are reached by utilizing the dot (.) operator, enabling access to elements specified within the namespace like classes or functions.
Syntax:
It has the following syntax.
[Namespace_name].[member_name]
- Namespace_name: This defines the name of the namespace.
- Member_name: It denotes the entity within the namespace, like a class, function, interface, constructor, or delegate.
C# namespace Example:
Let's consider an example to showcase the concept of namespaces in C#.
Example
using System;
namespace C# Tutorial
{
class Message
{
public void Show()
{
Console.WriteLine("Hello from C# Tutorial");
}
}
}
class Program
{
static void Main()
{
// Creating object using fully qualified namespace
C# Tutorial.Message obj = new C# Tutorial.Message();
obj.Show();
}
}
Output:
Hello from C# Tutorial
Explanation:
In this instance, we've selected a namespace named C# Tutorial which encompasses a class named Message. Within this class, there is a method named Show responsible for displaying a message by utilizing the Console.WriteLine function. Within the primary function, we instantiate the class (Message) and invoke the Show method to showcase the results.
Namespace with using keyword
In C#, the employing keyword is utilized to add the namespaces in the program. It permits us to reach the classes, functions, and variables from that namespace without having to write out the complete namespace repeatedly.
Syntax:
It has the following syntax.
using namespace_name;
Here, the utilizing keyword is employed to integrate the namespaces in a program, and the namespace_name denotes the aggregation of classes, interfaces, and methods.
C# Namespace Example by 'using' keyword
Let's consider an illustration to demonstrate the concept of namespaces using the keyword in C#.
Example
using System;
using Library;
using Student;
namespace Library
{
public class Book
{
public void ShowBook()
{
Console.WriteLine("This is the Library Namespace - Book Class");
}
}
}
namespace Student
{
public class Info
{
public void ShowStudent()
{
Console.WriteLine("This is the Student Namespace - Info Class");
}
}
}
public class TestNamespace
{
public static void Main()
{
Book b1 = new Book();
Info s1 = new Info();
b1.ShowBook();
s1.ShowStudent();
}
}
Output:
This is the Library Namespace - Book Class
This is the Student Namespace - Info Class
Explanation:
In this instance, we've utilized two namespaces, namely Library and Student. Within the Library namespace, there exists a Bool class featuring the ShowBook method, while the Student namespace houses an Info class with the ShowStudent method. The "Using" keyword is employed at the beginning of the program to enable direct access to these classes. Within the main method, we instantiate objects and invoke their respective methods (ShowBook, ShowStudent) to display the desired output.
Nested Namespace
In C# programming language, nested namespaces enable us to specify a namespace within another namespace. This feature is beneficial for structuring code in a hierarchical manner, preventing namespace duplication, and improving code readability.
C# Nested Namespace Example
Let's consider a scenario to demonstrate the concept of nested namespace in C#.
Example
using System;
namespace Company
{
namespace HR
{
class Employee
{
public void ShowEmployee()
{
Console.WriteLine("This is the HR namespace - Employee class");
}
}
}
namespace Finance
{
class Account
{
public void ShowAccount()
{
Console.WriteLine("This is the Finance namespace - Account class");
}
}
}
}
class Program
{
static void Main()
{
// Access nested namespaces
Company.HR.Employee emp = new Company.HR.Employee();
emp.ShowEmployee();
Company.Finance.Account acc = new Company.Finance.Account();
acc.ShowAccount();
}
}
Output:
This is the HR namespace - Employee class
This is the Finance namespace - Account class
Explanation:
In this code snippet, we've utilized the company namespace with two nested namespaces: HR and Finance. The HR namespace hosts the Employee class, while Finance includes the Account class. Both classes feature methods named ShowEmployee and ShowAccount. Within the main method, instances of these classes are instantiated, and their respective methods are invoked to display the output.
C# Built-in Namespace
In C# programming, a namespace serves as a storage unit for methods, classes, and interfaces. It includes numerous predefined namespaces that house built-in classes and methods accessible for direct utilization within our code.
C# Example Built-in Namespace
Let's consider a basic illustration of a predefined namespace in C#.
Example
using System; // Built-in namespace
class Program
{
static void Main()
{
// Console class
Console.WriteLine("Hello from System Namespace");
// Apply Math class
int number = 16;
double res = Math.Sqrt(number); // calculate Square root of number
Console.WriteLine("The square root of " + number + " = " + res);
}
}
Output:
Hello from System Namespace
The square root of 16 = 4
Explanation:
In this instance, we are utilizing the predefined System namespace. The console class serves the purpose of displaying messages, whereas the math class facilitates mathematical computations. The square root is computed using the Math.Sqrt method. Ultimately, the output is displayed using the Console.WriteLine function.
# Global Namespace
In C# programming language, the global namespace serves as the primary namespace housing all other namespaces like System, MyApp, Library, and more. To reference the root namespace directly, utilize global( ::).
C# Global Namespace Example
Let's consider a scenario to demonstrate the global namespace in C#.
Example
using System;
namespace MyApp
{
// Custom namespace
namespace System
{
class Console
{
public static void WriteLine(string msg)
{
// Use the global System.Console to avoid recursion
global::System.Console.WriteLine("Custom message " + msg);
}
}
}
class Program
{
static void Main()
{
// Calls our custom Console
System.Console.WriteLine("Hello");
// Calls the real System.Console from global namespace
global::System.Console.WriteLine("Hello C# Tutorial");
}
}
}
Output:
Custom message Hello
Hello C# Tutorial
Explanation:
In this instance, we establish the customized System.Console class within the MyApp namespace. When we invoke System.Console.WriteLine("Hello"), it interacts with the customized class, which displays output through the actual console accessed by global::System.Console. The global(::) keyword facilitates accessing the original .NET Console.
C# Example to Access Classes using a fully qualified namespace name
Let's consider a scenario in C# where a namespace in one program interacts with another namespace in a separate program.
Example
using System;
namespace School
{
public class Student
{
public void Show()
{
Console.WriteLine("This is a Student from School Namespace");
}
}
}
namespace College
{
public class Student
{
public void Show()
{
Console.WriteLine("This is a Student from College Namespace");
}
}
}
public class TestNamespace
{
public static void Main()
{
School.Student s1 = new School.Student();
College.Student s2 = new College.Student();
s1.Show();
s2.Show();
}
}
Output:
This is a Student from School Namespace
This is a Student from College Namespace
Explanation:
In this instance, we establish two namespaces called School and College, each housing the class named Student. Within the main function, we instantiate the class (Student) and invoke the Show method to display the result.
Conclusion
In summary, a C# namespace plays a crucial role in structuring code effectively. It is essential for managing the scope of classes and methods within a substantial .NET project, enhancing code organization and coherence. Moreover, it serves to mitigate naming clashes and enhance code readability.
C# Namespace FAQs
1) What is the namespace in C#?
In C#, a namespace functions as a package that encompasses functions, classes, and interfaces. It serves to manage the visibility of functions and classes within an extensive .NET project, enhancing code organization and structure. Within a C# application, we reference System.Console, with "System" representing the namespace and "Console" representing the class.
2) Why are the namespaces important in C#?
In C#, the namespace plays a crucial role by facilitating the structured organization of code and effectively avoiding naming clashes, thereby enhancing the code's readability.
Yes, it is possible for two namespaces to share the same name in C#.
Yes, identical namespaces can be present in different files and assemblies.
4) What is a built-in namespace in C#?
In C#, a namespace serves as a container for organizing methods, classes, and interfaces. C# offers various default namespaces that include predefined classes and functions that can be readily employed within our codebase.
5) Can a namespace be nested in C#?
Yes, we can use multiple namespaces in C#.
namespace OuterNamespace
{
namespace InnerNamespace
{
classMyClass { }
}
}