![]() |
Namespaces are used to organize the classes. It helps to control the scope of methods and classes in larger .Net programming projects. In simpler words you can say that it provides a way to keep one set of names(like class names) different from other sets of names. The biggest advantage of using namespace is that the class names which are declared in one namespace will not clash with the same class names declared in another namespace. It is also referred as named group of classes having common features. The members of a namespace can be namespaces, interfaces, structures, and delegates. Defining a NamespaceTo define a namespace in C#, we will use the namespace keyword followed by the name of the namespace and curly braces containing the body of the namespace as follows: Syntax: namespace name_of_namespace { // Namespace (Nested Namespaces) // Classes // Interfaces // Structures // Delegates } Example: // defining the namespace name1 namespace name1 { // C1 is the class in the namespace name1 class C1 { // class code } } Accessing the Members of NamespaceThe members of a namespace are accessed by using dot(.) operator. A class in C# is fully known by its respective namespace. Syntax: [namespace_name].[member_name] Note:
Example:
Output: Hello Geeks! In the above example:
The using keywordIt is not actually practical to call the function or class(or you can say members of a namespace) every time by using its fully qualified name. In the above example, System.Console.WriteLine(“Hello Geeks!”); and first.Geeks_1.display(); are the fully qualified name. So C# provides a keyword “using” which help the user to avoid writing fully qualified names again and again. The user just has to mention the namespace name at the starting of the program and then he can easily avoid the use of fully qualified names. Syntax: using [namespace_name][.][sub-namespace_name]; In the above syntax, dot(.) is used to include subnamespace names in the program. Example: // predefined namespace name using System; // user-defined namespace name using name1 // namespace having subnamespace using System.Collections.Generic; Program:
Output: Hello Geeks! Nested NamespacesYou can also define a namespace into another namespace which is termed as the nested namespace. To access the members of nested namespace user has to use the dot(.) operator. For example, Generic is the nested namespace in the collections namespace as System.Collections.Generic Syntax: namespace name_of_namespace_1 { // Member declarations & definitions namespace name_of_namespace_2 { // Member declarations & definitions . . } } Program:
Output: Nested Namespace Constructor |
Reffered: https://www.geeksforgeeks.org
C# |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 8 |