Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespaces and Using Directives

If I have a namespace like:

namespace MyApp.Providers
 {
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Globalization;
  }

Does this mean that if I create other files and classes with the same namespace, the using statements are shared, and I don't need to include them again?

If yes, isn't this a bit of a management headache?

like image 592
JL. Avatar asked Jul 20 '09 22:07

JL.


People also ask

Should using directives be inside or outside the namespace?

The using directive can appear: At the beginning of a source code file, before any namespace or type declarations.

What is namespace and its use?

A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.

What is the purpose of the using directive?

The primary function of the using directive is to make types within a namespace available without qualification to the user code. It considers the set of namespaces and types which are defined in referenced assemblies and the project being compiled.

What are the two types of namespaces?

When creating a namespace, you must choose one of two namespace types: a stand-alone namespace or a domain-based namespace. In addition, if you choose a domain-based namespace, you must choose a namespace mode: Windows 2000 Server mode or Windows Server 2008 mode.


2 Answers

No, it's only good for the namespace section inside the file. Not for all files inside the namespace.

If you put the using statement outside the namespace, then it applies to the entire file regardless of namespace.

It will also search the Usings inside the namespace first, before going to the outer scope.

like image 160
Brandon Avatar answered Sep 20 '22 10:09

Brandon


You need to specify the using directive for any classes that you want to reference without qualification in each file where you want to use them.

Reference:

The scope of a using directive is limited to the file in which it appears.

like image 44
tvanfosson Avatar answered Sep 19 '22 10:09

tvanfosson