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.
Related
This question already has answers here:
Duplicated using directives in multiple files
(2 answers)
Closed 2 years ago.
I have a number of using directives declaring the namespaces I am going to use in multiple classes.
Is there a way to refer multiple using statements via a single using directive or any other approach to this solution that I can implement for all the classes?
The classes/files might or might not be under the same namespace.
Example :
//Fil1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
namespace NS1
{
public class1
{
}
}
The reason to encapsulate these using statements is because they'll be common among multiple files.
//Fil2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
namespace NotNS1
{
public class2
{
}
}
Would prefer if there were some way to just make one using directive call in the class and define all these using statements elsewhere. Thanks.
Theres no magic using or #include like in the C world. You have to be explicit in each file or namespace what you are using.
Many tools, including Visual Studio, ReSharper and Rider include tools to help manage using directives.
No, but IDEs usually handle imports quite well, but you can place all your classes in a single namespace and import that, even tho thats very bad practice.
The first statement of all my C# files is "using System;".
Now with framework version 4 this namespace contains a class called "Action". This is also the name for a class im my own code in a regularly used namespace. Now there is of course a conflict. Ofcourse I can resolve this conflict by using explicit "MyNamespace.Action" where ever I was using "Action" before. This are several hundreds if not thousands of lines. Or I could not use the System namespace, which of course leads to many other problems. I would like to write something like "using System but not System.Action", but I cannot find a statement to do this.
Any ideas?
No, you can't.
But you can add using Action = MyNamespace.Action. This will be highly confusing for new developers, though, as Action is a fundamental part of .net since 3.5 so I strongly suggest you rename your class.
The using directive has two uses:
To permit the use of types in a namespace so you do not have to qualify the use of a type in that namespace:
using System.Text;
To create an alias for a namespace or a type (you could go for this one).
using Project = PC.MyCompany.Project;
The using keyword can also be used to create using statements, which define when an object will be disposed. See using statement for more information.
using directive (C# Reference)
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.
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.
For example:
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Security;
using System.Data;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.Web.Configuration;
using System.Collections.Generic;
I have something like that in a class that I have inherited. I could remove each namespace one by one to see if the class builds, BUT does it matter?
If I am not sure if System.Xml is needed, should I remove it?
In general all they do is add clutter.
However, they can in some specific circumstances cause problems with duplicate names in scope, or duplicate extension methods. For example, if there are classes Foo.SomeType and Bar.SomeType, and you have using Foo; and using Bar;, then references to SomeType will need disambiguating. The extension methods work similarly where static classes in different namespaces contribute conflicting extension methods.
The VS2008 tools (including express) include options to remove unnecessary using statements, which is very useful for tidying the code.
In general I like to remove unused using statements as they clutter up the code.
ReSharper grays out unused using statements.
It has a right click menu for, "Remove unused using statements" also.
Using statements are only used by the compiler for type resolution so feel free to remove them if they are not needed. Having extra will not hurt performance and removing them will only slightly improve compilation time.
If classes with simular names exists in different namespaces it could make it harder to follow the code.
The unused ones will be removed on compile time so it makes no difference, don't worry.
Here is probably the definitive post on performance of using statements: Do namespace using directives affect Assembly Loading?
The only harm it could cause would be if two of the namespaces happened to have a class of the exact same name within it: but at that point, the IDE would warn you.
Code tools will tell you if they are superfluous. I would just leave them. They don't do any harm. (Resharper for instance)
In the past when I manually hand removed unused INCLUDEs, it had no effect on memory or speed.
As others have mentioned here, there could be collision issues but if they're all .NET classes, I wouldn't worry too much about it.