This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Should Usings be inside or outside the namespace
So there are two approaches to where you have your using statements in regard to the namespace. You can either have them outside the namespace declaration or inside. What is the pro/con between the two approaches and which is generally preferred.
using System;
namespace MyNamespace
{
}
or:
namespace MyNamespace
{
using System;
}
I typically see the former in use. These using statements are typically at the very top of a source file, making it easy to see at a glance what a particular file makes use of. It also allows you to easily see the start of new code, as the namespace signals the new stuff.
The other way is a little bit less easy to follow from an organizational standpoint. The only benefit is that you could have different using statements in two different namespaces in the same file, but using two namespaces in the same place like that is bad coding practice, so it should be avoided.
Related
This question already has answers here:
Importing nested namespaces automatically in C#
(7 answers)
Closed 4 years ago.
I am a new c# learner, that' why I have some of the dumbest question! But I want to know if we have already used "using System" statement in our app then why do we need to use statements like "using System.Data" or any other shown in the image. Haven't we already imported the main namespace, then why is there even need of adding using statements for sub-namespaces?
Because the Language Spec says so:
C# language specification section 9.4.2 Using namespace directives:
A using-namespace-directive imports the types contained in the given namespace, but specifically does not import nested namespaces.
A reason for this might be that if every nested namespace is imported, then there would be too many name conflicts. This reduces the benefits of using using directives.
Here are some name conflicts that I could think of if using directives imported nested namespaces:
System.Drawing.Path and System.IO.Path
System.Windows.Forms.Button and System.Web.UI.WebControls.Button
System.Timers.Timer, System.Threading.Timer and System.Windows.Forms.Timer
Because using is not recursive down the namespace tree.
When you import System you import only the definitions strictly inside System not the ones inside System.Collections.
That's why you need to specify them.
This question already has answers here:
Using Statements vs Namespace path? C#
(6 answers)
Closed 8 years ago.
I want to use Console.WriteLine method. There are two ways
using System; and then Console.WriteLine(); this is one way
System.Console.WriteLine(). this is another way
What is the difference between these two?
Will all the classes include under system namespace if i use using System; ?
Will console class only include when i use System.Console.WriteLine statement?
using System is just a syntactic sugar that allows you to access all the classes under the namespace without specifying the namespace. So yes, using System imports all the classes that are defined in System namespace then you can access them by their name.
In case where you include two namespaces that has two identical class then you will have to use fully-qualified name of the class to avoid ambiguity.
Also it is worth noting that this is just a shortcut. The using directive doesn't add anything to your project.So if you need to use a class or a function from a third-party dll, first you have to add a reference to your assembly (*.dll file) then you can use using directive.
using System;
<CODEHERE>
<CODEHERE>
Console.WriteLine("Text");
<CODEHERE>
<CODEHERE>
This is the more generic, and usual way of doing it for two reasons:
It is more readable
And if you wanted to use another class of System, you would already have the import.
Using the other method:
System.Console.WriteLine("Text");
is a lot more rare to see, and you would have to write out the fully qualified name of any other System class, or just to use it again:
System.Console.WriteLine("Text");
System.Console.WriteLine("Text2");
If you look back at what the using statement actualy means:
'Using' is a statement used to stop the programmer from repeatedly having to type the fully qualified namespace for everything.
I would use the 'using System' version.
This question already has answers here:
Importing nested namespaces automatically in C#
(7 answers)
Closed 9 years ago.
so my program has these 2 lines at the beginning
using System;
using System.IO;
Question: Is the second statement actually necessary to include Sytem.IO methods and properties in my code?
It seems that 'System.IO' is a 'child' of the namespace 'System'. Shouldn't the first line grab all the child namespaces too? Or Do I not understand namespaces correctly?
System.IO namespace is used for Input Output operations.(Ex: File Operations)
System namespace does not include all child namespaces.
So if you want to perform IO Operations you should include System.IO namespace explicitly.
First Question : Is the second statement actually necessary to
include Sytem.IO methods and properties in my code?
Yes it is Necessary as System namespace does not include Child namespaces.
Second Question : It seems that 'System.IO' is a 'child' of the
namespace 'System'.
Yes System.IO is a Child of System namespace.
Note : though System.IO is a child namspace of System, it will not be included when you include System namspace
Third Question : Shouldn't the first line grab all the child
namespaces too? Or Do I not understand namespaces correctly?
No first line using System; does not grab all the Child namespaces as it is not java to import all child namspeaces using wild card character star *
C# is not like java, where you can use wildcards to import namespaces.
using System;
in C# is not the same as
import system.*;
in Java.
And that's really all there is to it. You need to explicitly include namespaces - not much more to say about it :)
Shouldn't the first line grab all the child namespaces too? Or Do I not understand namespaces correctly?
No - it will only make an alias for types in the System namespace directly. "Nested" namespaces (such as System.IO) are not made aliases automatically in C#. This is mentioned in the help for the using directive (italics added by me for emphasis):
allow the use of types in a namespace so that you do not have to qualify the use of a type in that namespace
You would still need to qualify IO for IO operations. For example, if you wanted to use the Path class, you'd need:
var filename = System.IO.Path.GetFilename(fullPath);
To expand on the other answers, there really aren't "child namespaces". There's nothing stopping you from declaring your own System.IO. You wouldn't want to of course, but you don't need a parent System namespace to do it.
You may have a project that by default has MyCompany.MyProject namespace, but you could just as easily declare XYZ.Some.Other.Random.Namespace in another .cs file of the same project. There's no inheritance to namespaces and XYZ.Some.Other doesn't exist. C# will let you use it, however, when you try to instantiate your class using the rest of it (Random.Namespace), it doesn't know how to find the class and won't resolve until you fully qualify the namespace in the using or fully qualify your variable declaration.
When I create a new class file in C#, the usual structure is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UnitTest
{
class Class1
{
}
}
StyleCop doesn't like having using directives outside of the namespace, so ideally, I would refactor my code as such:
namespace UnitTest
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Class1
{
}
}
From my days as a Java programmer, I was taught that it was better to import only the references that were necessary, rather than the entire package like so:
import foo.bar.MyObject;
instead of
import foo.bar.*;
I know that this can also be done in C#, with the added feature that you can use aliases for types (sometimes useful when working though native code):
using StringBuilder = System.Text.StringBuilder;
or when using aliases:
using HANDLE = System.IntPtr;
using HDC = System.IntPtr;
So my questions, regarding best practice and efficiency of using directives:
Is is more efficient to keep using statements inside a namespace, or is this purely a stylistic preference?
If is more efficient to only include the necessary items, as opposed to the entire namespace?
There are some fringe cases where it makes a difference but for the majority of cases it is just a stylistic preference.
The using statements just tell the compiler where it can locate the types. It has no influence on the runtime.
nope; stylistic preference, as long as it doesn't introduce any semantic changes; the cases where it changes the meaning are very rare (although there used to be a bug with the LINQ-to-SQL code generator that did care about where you put them - this is now fixed)
nope; unused directives are not used, and they don't massively impact the compiler
Note that having too many directives can cause ambiguities; for example there are a myriad of classes called Timer. For that reason it is worth keeping things tidy.
Almost all C# files have using statements at the top of the page
i.e.
using System;
using System.IO;
//code....
What do the using statements mean that are at the top of the page? Why is the syntax different from other using statement declarations.
i.e.
using (ResourceType resource = expression) statement
Those are using directives. They tell the compiler which namespaces to look in to find the classes you use in your code.
They look different (and are completely different) from the using statement which defines a scope for disposable objects.
These statements tellt he compiler which namespaces to look in to find the classes you are using in the code.
For example if you have
using System.IO;
Then your code to read all text of a file can be
File.ReadAllText("MyFile.txt");
rather than
System.IO.File.ReadAllText("MyFile.txt");
The using directive (as opposed to the using statement you mention that handles disposable objects) allow you to not specify the whole namespace of a class
i.e. if there is a class called
System.IO.FileStream
Then you could put
using System.IO;
And refer to it as
FileStream
(as long as the compiler can only determine a single thing that might mean)
using is a contextual keyword; it has more than one meaning, depending on how it's used.
At the head of a .cs file, it works like the java import instruction, specifying namespaces to search when looking for a type. If it's not listed, you must fully qualify types you use, which gets cumbersome. However, importing namespaes you don't need is wasteful and can introduce ambiguities.
Check out http://msdn.microsoft.com/en-ca/library/zhdeatwt(v=VS.80).aspx
The using keyword has two major uses:
As a directive, when it is used to
create an alias for a namespace or to
import types defined in other
namespaces. See using Directive.
As a statement, when it defines a
scope at the end of which an object
will be disposed. See using Statement.
1) The using keyword followed by a resource path provides a reference to a library in order to use additional/special classes and methods. This is similar to import-like keywords in other languages.
2) The using statement obtains the resource specified, executes the statements and disposes the object (releases from memory).
The kind of usings that exists are the
using directive, the one on top of files. It has two versions
using System.Text; - search this namespace for types that are not given by a fully qualified name. Similar to the %PATH% system variable.
using Project = PC.MyCompany.Project; - an "alias" for a type or namespace
The other kind of using is the using statement, the one with using (var foo = IDisposable){...}
This is a shortcut for a try-catch-block that calls Dispose on the foo-variable at the end.