c# using statements placement [duplicate] - c#

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Should Usings be inside or outside the namespace
I am looking at a code base where the author (one I respect) consistently places using statements inside of the namespace, as opposed to above it. Is there some advantage (more efficient GC?) to doing so or is this just a code style preference?
Cheers,
Berryl

Never put them inside without using "global::" or your code will become brittle.
namspace bar {
using foo //this may mean "using global::bar.foo OR using global::foo"
}
Reference
http://blogs.msdn.com/b/ericlippert/archive/2007/06/25/inside-or-outside.aspx?wa=wsignin1.0

If you have multiple namespaces in the same file then you will be scoping usings only to the containing namespace instead of to all namespace in the entire file.
Also see (just found this good explanation) Should 'using' statements be inside or outside the namespace?

Scott Hanselman did a post about this back in July 2008. I don't know if this changed with the .NET 4 framework, but it basically came down to being a preference issue unless you're naming your classes the same as existing classes as well as multiple namespaces in a single file.

It's a preference thing but there is a semantic difference when you use the statement on the inside versus on the outside in some scenarios.
using Bar;
namespace Foo
{
using Bar;
namespace Bar
{
class C
{
}
}
namespace Baz
{
class D
{
C c = new C();
}
}
}
namespace Bar
{
class E
{
}
}
In this, the outer using statement refers to the namespace Bar that is after namespace Foo. The inner using statement refers to Bar that is inside Foo. If there were no Bar inside Foo, then the inner would also refer to the outer Bar.
Edit And as Jonathan points out, the inner using can be changed to `using global::Bar;" to refer to the out Bar namespace, which would happen to break this particular code because of D trying to use C.

It's MS recommend practice. Programs such as stylecop recommend it.
Check out Is sa1200 All using directives must be placed inside the namespace (StyleCop) purely cosmetic? for a more in-depth discussion

Related

namespaces and using scope resolution [duplicate]

This question already has answers here:
C#: Difference between using System.Text and System.Text.RegularExpressions
(3 answers)
Nested namespaces
(6 answers)
Using nested namespaces [duplicate]
(3 answers)
Closed 5 years ago.
I have run across something I find odd in C# .NET Core 2.0 and I am wondering what is going on here.
I have a file called FooBar.cs and it looks like this
namespace Foo
{
public class FooClass
{
}
namespace Bar
{
enum BarEnums
{
Bar1
,Bar2
,Bar3
}
}
}
And I have a simple program that looks like this
using System;
using Foo;
namespace Using
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
FooClass fooClass = new FooClass();
Console.WriteLine(Bar.BarEnums.Bar1);
}
}
}
This gives me the following error:
Program.cs(16,22): error CS0103: The name 'Bar' does not exist in the current context
I am confused as to why the using statement exposes the class within the name space but it does not expose the namespace also found at the same level? If I put in using Foo.Bar it still gives the same error.. so the using statement can see the namespace but it does not help it find the references below.
Now if I put in Foo.Bar.BarEnums.Bar1 it will work just fine.. But why do I not have to put in Foo.FooClass following the same nomenclature as with the reference to the enums? Is this just a difference between accessing enums vs classes from within a namespace?
That happens because using Foo only imports the types contained in the given namespace, but it does not specifically import the nested namespaces. So that´s why when you reference your enum you have to do it with the full namespace reference.
This is a C# language specification.
Here is an explanation from a guy from the C# team:
In C#, when you specify a “using” clause, such as
using System.Text;
the compiler only imports the types in System.Text into the global
namespace – it doesn’t do the same with any namespaces inside of
System.Text. So, while that using allows me to write:
StringBuilder s = new StringBuilder();
it does not allow me to write:
RegularExpressions.Regex r = new RegularExpressions.Regex();
Why?
Well, an early version of the C# compiler had that behavior, but we
found that it had a few issues:
First, it made the code harder to follow. In the above example,
RegularExpressions.Regex() could be a global name, or a name based on
any of my using clauses. Having to look at the top of your code to
figure out what a name is is something we’d like to avoid.
The second problem had to do with collisions between namespace names,
which occurred much more often with this behavior. If there was
another namespace with a RegularExpressions namespace inside of it,
the user wouldn’t be able to have a “using” statement for both – even
if they didn’t actually care about that namespace.
We therefore decided to change the behavior.
https://blogs.msdn.microsoft.com/csharpfaq/2004/03/07/why-dont-namespace-using-directives-import-nested-namespaces/
And here is the C# spec: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/namespaces

C# unit (file-wide) namespace

I read C# spec and googled for it, but found nothing.
I am 99% sure there is no such feature like unit namespace directive in C#, but the question is: why? Are there idiomatic or technical reasons?
It is convenient, especially when most of our file consist of single namespace.
Is there any feature requests or proposals out there? Maybe we can make one?
// with unit namespace
namespace Foo;
class Bar { ... } // Class Bar declared inside Foo Namespace
struct Baz { ... } // Baz is inside Foo too
// without
namespace Foo {
class Bar { ... }
class Baz { ... }
}
Or maybe there is a way to re-export global symbols?
I mean first you declare everything inside global namespace, and then
publish public symbols in selected namespace?
The deep nesting of C# code is one of the most annoying thing for me.
I really enjoyed C++ ability to forward declare even nested classes and then define them without even 1 extra level of nesting.
Thanks for your time.
Logically, namespaces are block, just like classes, except that they can only contain types, not members.
Having a special syntax for this kind of block would be pointless and confusing.

How does C# pick when two class names collide

I have the following two files:
IGlobalApiProvider.cs
using System.Collections.Generic;
using Vert.Slack;
namespace Vert.Interfaces
{
public interface IGlobalApiProvider
{
List<Im> ImList();
}
}
And the corresponding implementation: SlackApi.cs
using System.Collections.Generic;
using Vert.Interfaces;
namespace Vert.Slack
{
public class SlackApi : IGlobalApiProvider
{
public List<Im> ImList()
{
...
}
}
}
Now, Intellisense is telling me that when I use IM in IGlobalApiProvider it's resolving to Im, which is defined in a file named RtmStart.cs which has no namespace declaration. When I use IM in SlackApi.cs, it's resolving to Vert.Slack.Im which is defined in the Vert.Slack namespace in a file named Im.cs. The weird behavior alerted me to the redundant definition, so I removed it and things are working fine.
However, I'm confused about why Visual Studio behaved differently in these two ways. I can tell something was scanning for the class names in a different pattern in the two situations. I can also tell that being used in the same namespace vs being used in a class that uses the namespace seems to be the trigger. What I don't know is what mechanism controls the logic behind this behavior.
Can anyone shed light on this?
Everything you see is contained in Vert.dll, which consists of one project, Vert.csproj
Link to the four files mentioned in this post as they existed at the time of writing.
This has to do with the difference between the global and Vert.Slack namespaces.
The compiler looks for the most explicit namespace with the proper class defined.
In this example, when the compiler looks for the definition of Im in IGlobalInterfaceProvider.cs, there is no namespace defined (or used) in this file that contains the class, but Im is also defined in this file - which is declared in the global namespace.
When the compiler looks for the definition of Im in SlackApi.cs, Im is found in the explicit Vert.Slack namespace, and utilizes that class.
The answer here is a similar topic and may provide more insight.
This may be related to the fact that your namespaces are in the wrong place ;-)
http://www.stylecop.com/docs/SA1200.html
This answer here gives a good explanation: Should 'using' statements be inside or outside the namespace?

What is the difference between namespace dot namespace and nested namespace?

Is there any difference between:
namespace Outer.Inner
{
}
And
namespace Outer
{
namespace Inner
{
}
}
in C#?
Assuming you don't put any other declarations or using directives in the Outer namespace, there's no difference at all.
Given that you would very very rarely declare members in multiple namespaces within a single file, I'd suggest using the first form - aside from anything else it saves a level of indentation. Note that "brace at the start of a new line" is a more conventional bracing style for C# though:
namespace Outer.Inner
{
...
}
No difference whatsoever, those are the same thing, however the first one is more common.
No, but the first variant is the most used in c# code.
The second variant is what you'd have to write in C++ and I'm not sure I ever saw it in real c# code yet.
They both are the same as noted by other answers and per documentation here.
Also the fact the one namespace is defined inside another doesn't really mean that it has any special relationship with the parent or that it brings any particular features in relation with parent or that it depends on parent namespace. There is no relationship other than it's just defined inside parent (in context of using statement to bring them in).
As such, it is important to note that if you include the parent namespace, it doesn't meant the child names are now accessible. See this answer which explains this.
So despite the fact they are nested, for all practically purposes, each namespace is its own independent thing, no matter if its the top most parent or a child. You will always need to use fully qualified name of the nested namespace if you want to include it.
As such the dot(.) almost becomes part of the namespace much like you can have a gmail id as first.last#gmail.com
So why nested?
It really is just to logically place them as if they are in a hierarchy for benefit of organizing them but you can think of the dot in the name as part of the namespace (for all practical uses).
for example you can define this:
namespace Outer.Inner
{
class MyClass{}
}
But if you wanted, you can rename the above to the following for all practical purposes:
namespace Solar
{
class MyClass{}
}
In both cases if you want to use MyClass, you will need to include fully qualified name of the namespace where the class is defined which is:
using Outer.Inner;
or
using Solar;
This can best be understood and summarized in looking at C# library namespaces.
using System;
using System.Threading;
using System.Threading.Tasks;
So although, the above three lines contain nested namespaces, each line really is fully qualified name to a unique namespace (as if the dot is part of the namespace) and that should be useful to know in terms of the differences and usage.

C# Using Classes in Project

I have organised my project with separate folders for groups of classes, but now in order to get to any method I have to reference the whole path like:
Classes.Users.UsersClass.Get();
Classes.Database.ConnectionClass.Test();
if (!Classes.Database.UsersMethods.Authenticate())
{
Classes.Users.UsersClass.LoginFailed();
}
As you can see, this is going to get messy after a while, so is there a way I can just call the class directly?
/Edit
This is the fixed up version:
Users.GetWindowsUser();
Connection.Test();
if (!UserMethods.Authenticate())
{
Users.LoginFailed();
}
You can add a using directives at the top of your C# file:
using Classes.Users;
using Classes.Database;
This would then let you type:
UserClass.Get();
ConnectionClass.Test();
That being said, I would strongly recommend not using "Class" as a suffix on every class, and also recommend not using a namespace named "Classes". Most things in C# are classes - there is no need to suffix every class with this in terms of naming.
For details, please refer to the Namespace Naming and Class Naming guidelines on MSDN.
Add the appropriate using statement to the top of your file. E.g. using Classes.Database;
Also, in VS 2010 if you just type the name of the class without the namespace (e.g. ConnectionClass) then hit ctrl+. it will give you the option to automatically add the appropriate using statement.
you can simply put using directives on the top of the file, or
if you don't want the classes to be in separated namespaces go to the class file and change the namespace to project original namesapce
namespace myProject.SubFolder
{
.......
}
will be
namespace myProject
{
.........
}

Categories