C namespaces LEARNOVITA

Namespaces – The complete C# Tutorial

Last updated on 16th Aug 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) | 18557 Ratings 2046

Introduction to C# Namespace

Namespaces are declarative tags that want to convey data concerning the behavior of varied parts in your program, like categories, methods, structures, enumerators, and assemblies, to the runtime. you’ll use Namespaces to feature declarative data to your program. Declarative tags pictured by square brackets ([]) placed on top of the weather used. The Namespace is employed to feature data like compiler directions and different data like comments, descriptions, methods, and categories to the program. The .Net Framework provides 2 styles of Namespaces: predefined Namespaces and user-defined Namespaces.

Namespace specification

  • The syntax for specifying associate Namespace is:
  • [Namespace (positional_parameters, name_parameter = worth, …)]

element

The name of the Namespace and its worth are boxed in square brackets before the part to which the Namespace applies. point parameters specify vital data, and name parameters specify nonobligatory data.

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

Namespace Usage

The predefined NamespaceUsage Namespace describes the way to use the custom Namespace category. Specifies the sort of part that the Namespace will be applied to. The syntax for specifying this Namespace is:

Here, the validon parameter specifies the language part during which the Namespace will be placed. This is often a mixture of values in the NamespaceTargets functionary.

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

The default is fake (disposable). The heritable parameter (optional) provides a Boolean worth that’s the worth of the heritable property of this Namespace. If true, the derived category inherits the Namespace. The default is fake (not inherited).

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

Representing and Utilizing Custom Namespace categories in C#

The involved, half vogue improvement that organizations expect out of current programming engineers needs additional outstanding set up ability than the set up systems of the past.

Microsoft’s .NET Framework utilizes traits to offer additional quality through what’s referred to as “revelatory” programming. Ascribes improved ability in programming frameworks since they advance free coupling of quality. Since you’ll create your custom property categories and after following them, you’ll use the free coupling force of traits for your motivations.

The .NET Framework makes various components of Windows programming heaps easier. By and enormous, the Framework’s utilization of data that .NET compilers tie to congregations at associate combination time makes precarious programming additionally easy. To be sure, the employment of inborn data makes it practicable for .NET to calm the US from “DLL Hell.”

Conditional

This predefined Namespace marks a conditional methodology whose execution depends on a such preprocessing symbol. It causes conditional compilation of methodology calls, betting on the desired worth like correct or Trace. For instance, it displays the values of the variables while debugging a code.

Syntax for specifying this Namespace is as follows

  • #define correct
  • using System;
  • using System.Diagnostics;
  • public category Myclass
  • }
  • class check perform one.”);
  • function2();
  • }
  • static void function2() operate two.”);
  • }
  • public static void Main() perform.”);
  • function1();
  • Console.ReadKey();
  • }
  • }
  • When the on top of code is compiled and dead, it produces the subsequent the subsequent

    In Main operate

    In operate one

    In operate two

    This predefined Namespace marks a program entity that ought to not be used. This enables you to instruct the compiler to discard a specific target component. For instance, if a brand new methodology is employed in a category and you wish to keep the recent methodology within the category, you’ll be able to deprecate it by displaying a message to use the new methodology rather than the recent methodology.

    The syntax for specifying this Namespace is:

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

    The parameter message here could be a string that explains why the item was deprecated and what to use instead. The iserror parameter could be a Boolean worth. If it’s true, the compiler ought to treat the utilization of the component as a slip-up. The default is fake (the compiler can generate a warning). The subsequent program demonstrates this mistreatment of the system.

    • namespace namespace_name shows
    • }
    • To decision the namespace-empowered rendition of 1 or the opposite capability or variable, prepend the namespace name as follows − namespace_name.item_name; The incidental system exhibits utilization of namespaces
    • utilizing System;
    • namespace first_space
    • }
    • }
    • namespace second_space
    • }
    • }
    • class TestClass
    • }

    Whenever the on top of code is organized and dead, it delivers the incidental outcome

    • Inside first_space
    • Inside second_space

    When you attempt to compile a program, the compiler throws miscalculation message kind of like the following:

    Do not use OldMethod, use NewMethod instead.

    Create a custom Namespace

    Custom Namespace

    The .Net Framework permits you to form custom Namespaces that may be accustomed to store declarative data and retrieve it at run time. This data will be related to every target component supported standard and application wants. making and mistreatment custom Namespaces involves four steps

    Declaring custom Namespaces

    Creating custom Namespaces

    Apply custom Namespaces to focus on program parts

    Access to Namespaces by reflection

    The final step is to jot down a straightforward program to research the data and realize the assorted notations. data is data concerning the info, or data accustomed describe alternative knowledge. This program should use reflection to access the Namespaces at run time. this can be explained within the next chapter.

    Custom Namespace declaration

    The new custom Namespace should be derived from the System.Namespace category. Example:

    • // Custom Namespace BugFix appointed to a category and its members
    • [NamespaceUsage (
    • NamespaceTargets.Class |
    • NamespaceTargets.Constructor |
    • NamespaceTargets.Field |
    • NamespaceTargets.Method |
    • NamespaceTargets.Property,
    • AllowMultiple = true)]
    • public category DeBugInfo: System.Namespace

    In the previous code, we have a tendency to declare a custom Namespace referred to as DeBugInfo.

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

    Before you start to contemplate what you’ll bring home the bacon together with your custom property categories, however concerning we have a tendency to examine a little of the quality credits that the Common Language Runtime as of currently makes accessible. Will the [WebService] property provide a basic example?it permits you to rework any open strategy for a WebService taxonomic group into a way that you simply will uncover as an element of the online Service just by appending the [WebMethod] quality to the technical definition.

    You basically connect the [WebMethod] characteristic to the strategy and .NET handles all the opposite things for you within the background. Utilizing the [Conditional] quality permits you to create a given strategy contingent in light-weight of the presence or non-appearance of the preset preprocessing image. for example, the attendant code:

    namespace MyNamespace

    • interface MyInterface
    • struct MyStruct
    • enum Days
    • delegate void MyDelegate();
    • namespace MyNamespace.NestedNamespace
    • worker
    • }
    • }

    Custom Namespaces versus category Properties

    Clear similarities exist among characteristics and customary half properties of a category. this will build it exhausting to conclude once and wherever you ought to use a custom quality category. Designers usually touch the properties of a category and their qualities as being “credits’ ‘ themselves, therefore what really is that distinction among properties and traits?

    A characteristic takes one thing terribly kind of like “shape and structure” as a property after you characterize it, however you’ll connect it to all or any ways that of varied get-together level types? not merely categories. Table a pair of records of all of the gathering levels that you simply will apply characteristics to.

    Part properties of a category are to boot restricted in another manner by that credits don’t seem to be. By definition, a neighborhood property is connected to a specific category. That half property will at ANy purpose be used through an example or taxonomic group occasion of the category on which the property was characterized.

    Then again, you’ll join/apply ascribes anyplace! The most requirement is that the get-together type the property is being connected to matches the validation definition within the custom characteristic. I’ll speak a lot concerning the validation property of custom characteristic categories within the following section. This attribute of properties assists with advancing the free coupling that’s therefore helpful partly vogue advancement.

    One more distinction among properties and characteristics connects with the qualities you’ll store in all of them. The upsides of half properties are occasional esteems and might be modified at run-time.

    In any case, on account of traits, you set qualities at configuration time (in supply code) and later on incorporate the characteristics (and their qualities) squarely into the data contained in a very get-together. at the moment, you can’t amend the upsides of the Namespaces? you’ve remodeled the upsides of the traits into hard-coded, real simple data.

    Consider this after you connect an attribute. On the off probability that you simply connect a characteristic to a category definition, for example, every occasion of {the category|the category} can have similar qualities allotted to the property paying very little heed to the quantity of objects of this class sort you launch. You can’t be part of a characteristic of a category. you will simply be part of a characteristic to a Type/Class definition.

    Creating custom Namespaces

    Let’s produce a custom Namespace known as DeBugInfo that stores the data obtained by debugging the program. Save the subsequent information

    • Error code variety
    • The name of the developer UN agency known the bug
    • The date the code was last checked
    • String message to avoid wasting developer annotations
    • The DeBugInfo category has 3 non-public properties to store the primary 3 items of knowledge and one holding to store the message. Therefore, the bug variety, developer name, and review date area unit point parameters of the DeBugInfo category, and also the message is AN nonmandatory or named parameter.
    • Each Namespace needs a minimum of one creator.
    • Positional parameters should be passed via the creator.

    The following code shows the DeBugInfo class

    • utilizing System;
    • namespace ConsoleApplication1
    • public void show()
    • initial Namespace and count = ” + count);
    • }
    • }
    • }
    • namespace secondNamespace
    • public void show()
    • }
    • }
    • class Program
    • }
    • }

    Creating a Custom Namespace category

    Presently we’ll create a lot of sensible execution of the thoughts introduced antecedently. However, we tend to create a custom attribute category. This may allow America to store some following knowledge regarding code changes that you simply would commonly record as remarks within the ASCII text file. For the model, we’ll record solely some of things: deformity id, engineer id, the date of the modification, the start of the imperfectness, and a remark regarding the fix. to stay the model easy we’ll zero in on creating a custom characteristic category (DefectTrackNamespace) assigned for utilizing simply with categories and techniques. On the off likelihood that you simply haven’t used traits antecedently, the concomitant line of code could look a bit outre.

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

    This line connects a [NamespaceUsage] attribute to the property category definition. sq. section synchronic linguistics acknowledges the event as a high quality. During this method, Namespaces categories will have their traits.

    Applying the Custom Namespace

    You’ve as of currently seen that you simply will connect a characteristic to AN objective factor in your C# code by putting the standard name and its boundaries in sq. sections preceding the thing’s revelation articulation.

    In Listing a pair of you be a part of the [DefectTrack] quality to some techniques and some categories.

    You want to ensure that you simply approach the category definition for your custom characteristic therefore you begin by together with this line.

    utilizing MyNamespaceClasses ;

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

    Applying the Custom Namespace

    Applying the Custom Namespace

    A custom property affirmation starts with the System. NamespaceUsageNamespace, that characterizes a little of the essential qualities of your attribute category. For example, you’ll be able to indicate whether or not your qualities are often non-inheritable by totally different categories or confirm that elements the characteristic are often applied to. The Namespace is applied by putting it directly before its target

    • [DeBugInfo(45, “Zara Ali”, “12/8/2012”, Message = “Return kind mismatch”)]
    • [DeBugInfo(49, “Nuha Ali”, “10/10/2012”, Message = “Unused variable”)]
    • class parallelogram
    • [DeBugInfo(55, “Zara Ali”, “19/10/2012”, Message = “Return kind mismatch”)]
    • public double GetArea()
    • [DeBugInfo(56, “Zara Ali”, “19/10/2012”)]
    • public void Display() ”, length);
    • Console.WriteLine(“Width: ”, width);
    • Console.WriteLine(“Area: ”, GetArea());
    • }
    • }

    Conclusion

    Namespace provides a sturdy strategy for partner information, or definitive knowledge, with code (gatherings, types, techniques, properties, etc). When a property is said with a program component, the standards are often questioned at show time utilizing a technique known as reflection.

    Are you looking training with Right Jobs?

    Contact Us

    Popular Courses