Namespaces - The complete C# Tutorial
Namespaces in c Tutorial ACTE

Namespaces – The complete C# Tutorial

Last updated on 01st Feb 2022, Blog, Tutorials

About author

Manobala (C# Automation Tester )

Manobala is a C# automation tester and he has tons of experience in the areas of HTTP, SOAP/REST, VisualStudio, TFS, etc., CI/CD, functional, regression, and.NET technology stack. He spends most of his time researching technology and startups.

(5.0) | 18745 Ratings 1623
    • Introduction to C# Namespace
    • Namespace specification
    • Representing and Utilizing Custom Namespace Classes in C#
    • Conditional
    • How Accomplishes .NET Use Namespaces in the Common Language Runtime?
    • Custom Namespaces versus Class Properties
    • Creating custom Namespaces
    • The following code shows the DeBugInfo class
    • Creating a Custom Namespace Class
    • Applying the Custom Namespace
    • Applying the Custom Namespace
    • Conclusion

    Subscribe For Free Demo

    [custom_views_post_title]

      Introduction to C# Namespace

      Namespaces are declarative tags used to convey information about the behavior of various elements in your program, such as classes, methods, structures, enumerators, and assemblies, to the runtime. You can use Namespaces to add declarative information to your program. Declarative tags are represented by square brackets ([]) placed above the elements used. The Namespace is used to add metadata such as compiler instructions and other information such as comments, descriptions, methods, and classes to the program. The .Net Framework provides two types of Namespaces: predefined Namespaces and user-defined Namespaces.


      C# Namespace
      C# Namespace

      Namespace specification

      The syntax for specifying an Namespace is: –

      • [Namespace (positional_parameters, name_parameter = value, …)]
      • element

      The name of the Namespace and its value are enclosed in square brackets before the element to which the Namespace applies. Positional parameters specify important information, and name parameters specify optional information.


    • Predefined Namespaces
    • The .Net Framework provides three predefined Namespaces (NamespaceUsage)
    • Conditional
    • Abolition

    • Namespace Usage

      The predefined NamespaceUsage Namespace describes how to use the custom Namespace class. Specifies the type of element to which the Namespace can be applied. The syntax for specifying this Namespace is:

      Here, the validon parameter specifies the language element in which the Namespace can be placed. This is a combination of values ​​in the NamespaceTargets enumerator.

    • The default is NamespaceTargets.All. The allowmultiple parameter (optional) provides the value for the AllowMultiple property of this Namespace. This is a Boolean value. If true, the Namespace is reusable.

    • The default is false (disposable). The inherited parameter (optional) provides a Boolean value that is the value of the inherited property of this Namespace. If true, the derived class inherits the Namespace. The default is false (not inherited).

      • [NamespaceUsage (
      • NamespaceTargets.Class |
      • NamespaceTargets.Constructor |
      • NamespaceTargets.Field |
      • NamespaceTargets.Method |
      • NamespaceTargets.Property,
      • AllowMultiple = true)]

      Representing and Utilizing Custom Namespace Classes in C#

    • The intricate, part style improvement that organizations expect out of present-day programming engineers requires more prominent plan adaptability than the plan systems of the past.

    • Microsoft’s .NET Framework utilizes traits to give added usefulness through what is known as “revelatory” programming. Ascribes improved adaptability in programming frameworks since they advance free coupling of usefulness. Since you can make your custom property classes and afterward follow up on them, you can use the free coupling force of traits for your motivations.

    • The .NET Framework makes numerous parts of Windows programming a lot easier. By and large, the Framework’s utilization of metadata that .NET compilers tie to congregations at an aggregate time makes precarious programming more straightforward. To be sure, the utilization of inborn metadata makes it workable for .NET to calm us from “DLL Hell.”

    • Conditional

      This predefined Namespace marks a conditional method whose execution depends on a specified preprocessing identifier. It causes conditional compilation of method calls, depending on the specified value such as Debug or Trace. For example, it displays the values of the variables while debugging a code.


      Syntax for specifying this Namespace is as follows −

      • #define DEBUG
      • using System;
      • using System.Diagnostics;
      • public class Myclass {
      • [Conditional(“DEBUG”)]
      • public static void Message(string msg) {
      • Console.WriteLine(msg);
      • }
      • }
      • class Test {
      • static void function1() {
      • Myclass.Message(“In Function 1.”);
      • function2();
      • }
      • static void function2() {
      • Myclass.Message(“In Function 2.”);
      • }
      • public static void Main() {
      • Myclass.Message(“In Main function.”);
      • function1();
      • Console.ReadKey();
      • }
      • }

      When the above code is compiled and executed, it produces the following result −

    • In Main function
    • In Function 1
    • In Function 2

    • This predefined Namespace marks a program entity that should not be used. This allows you to instruct the compiler to discard a particular target element. For example, if a new method is used in a class and you want to keep the old method in the class, you can deprecate it by displaying a message to use the new method instead of the old method.


      The syntax for specifying this Namespace is:-

      • [Obsolete (
      • message)
      • )]
      • [Abolished (message, is an error)
      • )]]

      The parameter message here is a string that explains why the item was deprecated and what to use instead. The iserror parameter is a Boolean value. If its value is true, the compiler should treat the use of the element as an error. The default is false (the compiler will generate a warning). The following program demonstrates this using the system.


      • namespace namespace_name {
      • // code presentations
      • }

      To call the namespace-empowered rendition of one or the other capacity or variable, prepend the namespace name as follows − namespace_name.item_name; The accompanying system exhibits utilization of namespaces −

      • utilizing System;
      • namespace first_space {
      • class namespace_cl {
      • public void func() {
      • Console.WriteLine(“Inside first_space”);
      • }
      • }
      • }
      • namespace second_space {
      • class namespace_cl {
      • public void func() {
      • Console.WriteLine(“Inside second_space”);
      • }
      • }
      • }
      • class TestClass {
      • static void Main(string[] args) {
      • first_space.namespace_cl fc = new first_space.namespace_cl();
      • second_space.namespace_cl sc = new second_space.namespace_cl();
      • fc.func();
      • sc.func();
      • Console.ReadKey();
      • }
      • }

      Whenever the above code is arranged and executed, it delivers the accompanying outcome −

    • Inside first_space
    • Inside second_space

    • Course Curriculum

      Learn C# Certification Training Course to Build Your Skills

      Weekday / Weekend BatchesSee Batch Details

      When you try to compile a program, the compiler throws an error message similar to the following:

      Do not use OldMethod, use NewMethod instead.


      Create a custom Namespace

      The .Net Framework allows you to create custom Namespaces that can be used to store declarative information and retrieve it at run time. This information can be associated with each target element based on design criteria and application needs. Creating and using custom Namespaces involves four steps-


    • Declaring custom Namespaces
    • Creating custom Namespaces
    • Apply custom Namespaces to target program elements

    • Access to Namespaces by reflection

      The final step is to write a simple program to analyze the metadata and find the various notations. Metadata is information about the data, or information used to describe other data. This program must use reflection to access the Namespaces at run time. This will be explained in the next chapter.


      Custom Namespace declaration

      The new custom Namespace must be derived from the System.Namespace class. Example:


      • // Custom Namespace BugFix assigned to a class and its members
      • [NamespaceUsage (
      • NamespaceTargets.Class |
      • NamespaceTargets.Constructor |
      • NamespaceTargets.Field |
      • NamespaceTargets.Method |
      • NamespaceTargets.Property,
      • AllowMultiple = true)]
      • public class DeBugInfo: System.Namespace
      • In the previous code, we declared a custom Namespace called DeBugInfo.

      How Accomplishes .NET Use Namespaces in the Common Language Runtime?

      Before you begin to consider what you can achieve with your custom property classes, how about we inspect a portion of the standard credits that the Common Language Runtime as of now makes accessible. Does the [WebService] property give a basic example?it allows you to transform any open strategy for a WebService subclass into a technique that you can uncover as a component of the Web Service simply by appending the [WebMethod] quality to the technical definition.


      You essentially connect the [WebMethod] characteristic to the strategy and .NET handles all the other things for you in the background. Utilizing the [Conditional] quality permits you to make a given strategy contingent in light of the presence or non-appearance of the predetermined preprocessing image. For instance, the accompanying code:


      • namespace MyNamespace
      • {
      • class MyClass { }
      • interface MyInterface { }
      • struct MyStruct { }
      • enum Days { a, b }
      • delegate void MyDelegate();
      • namespace MyNamespace.NestedNamespace
      • {
      • class Employee { }
      • }
      • }

      Custom Namespaces versus Class Properties

    • Clear similitudes exist among characteristics and customary part properties of a class. This can make it hard to conclude when and where you should use a custom quality class. Designers generally allude to properties of a class and their qualities as being “credits” themselves, so what truly is the contrast among properties and traits?

    • A characteristic takes something very similar to “shape and structure” as a property when you characterize it, yet you can connect it to all ways of various get-together level types? not simply Classes. Table 2 records every one of the gathering levels sorts that you can apply characteristics to.

    • Part properties of a class are additionally restricted in one more manner by which credits are not. By definition, a part property is attached to a particular class. That part property can at any point be utilized through an example or subclass occasion of the class on which the property was characterized.

    • Then again, you can join/apply ascribes anyplace! The main prerequisite is that the get-together sort the property is being connected to matches the validation definition in the custom characteristic. I’ll speak more about the validation property of custom characteristic classes in the following segment. This trait of properties assists with advancing the free coupling that is so useful in part style advancement.

    • One more distinction among properties and characteristics connects with the qualities you can store in every one of them. The upsides of part properties are occasion esteems and can be changed at run-time.

    • In any case, on account of traits, you set qualities at configuration time (in source code) and afterward incorporate the characteristics (and their qualities) straightforwardly into the metadata contained in a get-together. After that point, you can’t change the upsides of the Namespaces? you’ve transformed the upsides of the traits into hard-coded, genuine just information.

    • Consider this when you connect a trait. On the off chance that you connect a characteristic to a class definition, for instance, each occasion of the class will have similar qualities allocated to the property paying little heed to the number of objects of this class type you launch. You can’t join a characteristic to an occurrence of a class. You may just join a characteristic to a Type/Class definition.

    • Course Curriculum

      Get JOB Oriented C# Training for Beginners By MNC Experts

      • Instructor-led Sessions
      • Real-life Case Studies
      • Assignments
      Explore Curriculum

      Creating custom Namespaces

      Let’s create a custom Namespace called DeBugInfo that stores the information obtained by debugging the program. Save the following information-


    • Error code number
    • The name of the developer who identified the bug
    • The date the code was last checked
    • String message to save developer annotations
    • The DeBugInfo class has three private properties to store the first three pieces of information and one public property to store the message. Therefore, the bug number, developer name, and review date are positional parameters of the DeBugInfo class, and the message is an optional or named parameter.
    • Each Namespace requires at least one constructor.
    • Positional parameters must be passed via the constructor.

    • C# Namespace
      C# Namespace

      The following code shows the DeBugInfo class-

      • utilizing System;
      • namespace ConsoleApplication1
      • {
      • namespace firstNamespace
      • {
      • class TutorialRide
      • {
      • int count = 1;
      • public TutorialRide()
      • {
      • count++;
      • }
      • public void show()
      • {
      • Console.WriteLine(“I am in First Namespace and count = ” + count);
      • }
      • }
      • }
      • namespace secondNamespace
      • {
      • class TutorialRide
      • {
      • int count = 2;
      • public TutorialRide()
      • {
      • count++;
      • }
      • public void show()
      • {
      • Console.WriteLine(“I am in Second Namespace and count = ” + count);
      • }
      • }
      • }
      • class Program
      • {
      • static void Main(string[] args)
      • {
      • firstNamespace.TutorialRide obj1 = new firstNamespace.TutorialRide();
      • secondNamespace.TutorialRide obj2 = new secondNamespace.TutorialRide();
      • obj1.show();
      • obj2.show();
      • Console.ReadLine();
      • }
      • }
      • }

      Creating a Custom Namespace Class

      Presently we’ll make a more practical execution of the thoughts introduced previously. How about we make a custom trait class. This will permit us to store a few following data about code changes that you would ordinarily record as remarks in the source code. For the model, we’ll record only a couple of things: deformity id, engineer id, the date of the change, the beginning of the imperfection, and a remark about the fix. To keep the model straightforward we’ll zero in on making a custom characteristic class (DefectTrackNamespace) assigned for utilizing just with classes and techniques. On the off chance that you haven’t utilized traits previously, the accompanying line of code may look a piece bizarre.


      • [NamespaceUsage(
      • NamespaceTargets.Class |
      • NamespaceTargets.Method,
      • AllowMultiple = true)]

      This line connects a [NamespaceUsage] trait to the property class definition. Square section grammar recognizes the development as a quality. In this way, Namespaces classes can have their traits.


      Applying the Custom Namespace

    • You’ve as of now seen that you can connect a characteristic to an objective thing in your C# code by placing the quality name and its boundaries in square sections preceding the thing’s revelation articulation.
    • In Listing 2 you join the [DefectTrack] quality to a few techniques and a few classes.
    • You want to guarantee that you approach the class definition for your custom characteristic so you start by including this line.

      • utilizing MyNamespaceClasses ;

      Past that you’re not kidding or “adorning” your class statements and a portion of your strategies with the [DefectTrack] custom property.


      Applying the Custom Namespace

      A custom property affirmation starts with the System. NamespaceUsageNamespace, which characterizes a portion of the critical qualities of your trait class. For instance, you can indicate whether your quality can be acquired by different classes or determine which components the characteristic can be applied to. The Namespace is applied by placing it immediately before its target −

      • [DeBugInfo(45, “Zara Ali”, “12/8/2012”, Message = “Return type mismatch”)]
      • [DeBugInfo(49, “Nuha Ali”, “10/10/2012”, Message = “Unused variable”)]
      • class Rectangle {
      • //member variables
      • protected double length;
      • protected double width;
      • public Rectangle(double l, double w) {
      • length = l;
      • width = w;
      • }
      • [DeBugInfo(55, “Zara Ali”, “19/10/2012”, Message = “Return type mismatch”)]
      • public double GetArea() {
      • return length * width;
      • }
      • [DeBugInfo(56, “Zara Ali”, “19/10/2012”)]
      • public void Display() {
      • Console.WriteLine(“Length: {0}”, length);
      • Console.WriteLine(“Width: {0}”, width);
      • Console.WriteLine(“Area: {0}”, GetArea());
      • }
      • }

      C and C Plus Plus Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

      Conclusion

      Namespace give a strong strategy for partner metadata, or definitive data, with code (gatherings, types, techniques, properties, etc). After a property is related with a program element, the quality can be questioned at show time to utilizing a method called reflection.


    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free