C# using statement at the top of the code page - c#

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.

Related

C# Using Directive - Including All Child Libraries [duplicate]

Sorry if this question was asked already.
I started studying C# and noticed that C# doesn't automatically import nested namespaces.
I don't understand:
using System;
should automatically import all classes contained in the System namespace right?
So there should be no need for me to write
using System.Windows.Form;
I would understand if using Windows.Form even worked. But the compiler could not resolve it! What is the point of the using System; before it then?
So why does using System; not import System.Windows automatically as well as System.Windows.Forms - sorry if the word import is wrong here.. maybe move to global namespace is the right terminology.
C# is not Java.
A using directive is used so you don't have to type in the fully qualified name of a type. It also helps with disambiguating type names (using aliases for instance).
In the case of Console, for example, you don't need to type System.Console.
It is important to understand the difference between a namespace and an assembly - a namespace is a logical grouping of types. An assembly is a physical grouping of types. Namespaces can span assemblies.
When you reference an assembly (this is more like importing a package in Java), you gain access to all of the public types in it. In order to use a type you need to uniquely identify it. This is done through the namespace - the using directive simply means you don't have to type the fully qualified name of the type.
The using directive has two uses:
To allow the use of types in a namespace so that 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. This
is called a using alias directive.
using Project = PC.MyCompany.Project;
http://msdn.microsoft.com/en-us/library/sf0df423.aspx
However, you have to note that System and System.Windows.Form are not connected through name itself in anyway. If you import (using) System that means you will use the System assembly types in this class. Actual reference you specify in references section in Visual Studio project which you can really use (even without using statement, as this is just a shortcut for types).
C# doesn't import nested namespaces and this is by design.
Namespace scope lets you organize code and gives you a way to create
globally unique types.
Nested namespaces are used to group related functionality, but use parts of it on-demand.
I guess you wouldn't want to have all the types from such a big namespace like System if the only thing you need is System.Windows.
So probably the question is why C# doesn't have something like using System.*; like java does. I don't know the answer, but I guess this is because of KISS principle. It's something like using
select *
you will never know what types you will add and how they will affect existing code.
Even in Java you'd have to explicitly write
import System.*;
Much of the time you don't want all of the nested namespaces. These would simply clutter IntelliSense.
The "using" syntax allows you shorthand access to namespaces that are already listed as References in the project settings. If the namespace is listed as a reference you already have access to it by it's full name without the "using" directive. Just saves keystrokes.
"Using" a given namespace means that you will get access to all definitions implemented directly in it, not that it will recursively look up the embedded namespaces; doing otherwise would defeat the purpose of the "Using" statement.
Namespaces exist to avoid class name ambiguity. The "Using" statement is here to avoid the use of fully qualified types nested in namespaces, when you know no (or little) ambiguity may occur.
No, this is not how it works.
And I will give a good argument against what you said: intellisnse would go crazy and finding the what you want would be hell.
You do have access to everything on every namespace available (with dots), the using keyword simplifies this because you don't have to specify from which namespace a class or struct is "coming from" (I mean, defined).

Including namespaces in C# [duplicate]

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.

Can "using <namespace>;" directives be made more efficient in .NET?

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.

exclude a class from a used namespace

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)

C# - Location of using statements

One thing I have noticed a lot of back and forth on is where using statements should be placed in a C# code file- whether its in the outermost scope or inside a namespace. I understand that the location of the using statement affects the scope of the references within that file, but what I don't understand is why, in most cases, someone would ever want their using statements inside their namespace.
In almost all cases only one namespace declaration ever exists in a single file so scoping the using statements seems/(is?) useless. If one were placing multiple types and multiple namespaces in the same file then scoped using statements make perfect sense, yet I still see plenty of cases of this being done even in files with one namespace. Why?
using System;
namespace MyNamespace
{
using System.Text;
public class MyClass {
// ...
}
}
An example of this being done throughout a project seemingly unnecessarily is the ASP.NET MVC source.
Putting "using" at the top of the files is the default way of Visual Studio. However, the recommended approach is putting the "using" statements inside of the namespace. Even MS's stylecop catches this and says the default way of VS is wrong.
Both techniques work fine.
StyleCop Rule says:
Placing multiple namespace elements
within a single file is generally a
bad idea, but if and when this is
done, it is a good idea to place all
using directives within each of the
namespace elements, rather than
globally at the top of the file. This
will scope the namespaces tightly, and
will also help to avoid the kind of
behavior described above.
It is important to note that when code
has been written with using directives
placed outside of the namespace, care
should be taken when moving these
directives within the namespace, to
ensure that this is not changing the
semantics of the code. As explained
above, placing using-alias directives
within the namespace element allows
the compiler to choose between
conflicting types in ways that will
not happen when the directives are
placed outside of the namespace.
Here's some links for further review:
Should 'using' statements be inside or outside the namespace?
Is sa1200 All using directives must be placed inside the namespace (StyleCop) purely cosmetic?
http://www.hanselman.com/blog/BackToBasicsDoNamespaceUsingDirectivesAffectAssemblyLoading.aspx
http://blogs.msdn.com/sourceanalysis/pages/sa1200-usingdirectivesmustbeplacedwithinnamespace.aspx
I'd never even seen/heard of this practice until I started using StyleCop and would get flagged by rule SA1200, which I now just disable. It's odd that the .cs files that Visual Studio creates as part of a new project violate this rule by placing the using directives at the very beginning of the file, outside of the namespace.
edited, with my head hanging in shame
Ahh! The using statement you're refering to is used to import a namespace, not to wrap an IDisposable object!
Very different, ambiguous terms... you had me confused :-)
Personally I like them outside the namespace at the top of the file; but it's probably due to me switching between C# and VB.NET.
I like to organize my projects into 1-file-per-class, no inner (nested) classes, and only one class per namespace (per file) . In this situation the location of the using statement is irrelevant whether inside or outside the namespace.
The iDesign C# coding standard is a solid standard to follow (or to derive your own from). It recommends keeping the using statements outside the namespace as item #14. But it's all down to your company / project's convention

Categories