I know C# supports namespace nestings, as does C++, which both allow code that looks like this...
namespace A {
namespace B {
...
}
}
Coming from a C++ background and diving into the C# world I've been meditating upon what appears as a hierarchical nesting of components via all the using directives that must be issued to exploit .NET, eg
using System.Collections;
using System.Collections.Generic;
I'm sure Microsoft intended and designed these libraries to be logically hierarchically organized, but without the aid of seeing the source I cannot verify if System.Collections.Generic has Generic as a nested namespace of Collections, but I assume it is, and that it was accomplished with namespace nestings like seen with A and B. Now once I start cooking up things in my own source and declaring code that looks like this
namespace C.D {
...
}
what exactly am I achieving here with respect to a hierarchy? Am I introducing to the code a singular namespace identifier "C.D" where the '.' is simply a friendly means of suggesting a hierarchy that may or may not exist depending upon the code structure or am I implicitly declaring two namespaces "C" and "D" with D nested within C? I've come across this question while cooking up a DevelopmentApplications namespace to our C# codebase that is meant to strictly contain all development tools used to augment our software to aid in its development. In those tools I've never declared a standalone enclosing namespace DevelopmentApplications (which is something I would HAVE to do in C++)...
namespace DevelopmentApplications
{
...
}
...but instead always create applications that go like
namespace DevelopmentApplications.MyDevelopmentApp
{
...
}
I know this area is a cause of confusion for some because of the following question where the author is struggling to understand the relationship between Foo.Bar.Baz and Foo.Bar. There's also an inverse question of a C# developer entering C++ land that gives some insight into this issue.
I suppose another way to state the question is that in C++ using the '::' operator to fully qualify a type I know guarantees that the code that type was declared in is nested deep in some namespace hierarchy. But in C# using the '.' operator to fully qualify some type must that type also exist in some deeply nested namespace hierarchy? I'm assuming here that C#'s use of a namespace like A.B.C does not necessarily require a hierarchical relationship between A B and C or that A B or C even exist as individual namespaces.
If someone can find or knows the relevant language specification regarding this syntax I'd love to read it.
Section 9.2 of the C# 4.0 specs states:
The qualified-identifier of a namespace-declaration may be a
single identifier or a sequence of identifiers separated by “.”
tokens. The latter form permits a program to define a nested namespace
without lexically nesting several namespace declarations. For example,
namespace N1.N2
{
class A {}
class B {}
}
is semantically equivalent to
namespace N1
{
namespace N2
{
class A {}
class B {}
}
}
You state:
I'm assuming here that C#'s use of a namespace like A.B.C does not necessarily require a hierarchical relationship between A B and C or that A B or C even exist as individual namespaces.
That assumption is false. The namespace A.B.C necessarily involves namespace A in the global namespace, namespace B within namespace A, and namespace C in namespace B.
Some facts about namespaces in C#:
They are collective. You can declare a namespace in several different source files, and the compiler will treat them all as the same namespace.
You can nest namespaces inside each other, but it's much more common to simply declare the nested namespace in another source file.
There is a global namespace, accessible to every class as global::
Related
Coming from C++ background myself, it takes some time to get used to C#. In C#, one uses the dot operator (.) more often than the ::-operator (the namespace qualifier operator in C#), to access namespace and class scopes.
In C++, one uses the dot operator (.) to access members of an instance of a class. Scope resolution operator (::) on the other hand, is used to access members of a class without an instance of that class. To me, this makes sense and is both logical and consistent.
While I can accept different approach used in C#, there seems to be at least one instance, in which I see an inconsistence. At least, that is how it appears to me. It has to do with the global keyword:
global::System.Console.WriteLine("Hello World");
Could somebody explain to me why namespace alias qualifier is required to use with global keyword instead of the dot operator?
It's not really common but there are some situations when it's handy.
Imagine you have this a class System inside current namespace:
namespace Test {
static class System {
public static Do() { }
}
class Foo {
void foo() {
System.Do(); // What's this?
}
}
}
Do you want to make it more complicate? Add an inner class in System and call it, for example, Action. Of course these are edge cases and probably you won't ever need to use global:: but language itself has to handle this situation. See MSDN for more examples.
Global namespace aliases are also useful in another situation: when you reference two DLLs and they have the same namespaces and classes (for example because they simply are the two versions of same stuff). In that case how can you reference them? Same problem described here for C++. You can change namespace to include version number but it's a pain each time you change it (and VS automatic refactoring AFAIK doesn't work with namespaces) or you can reference them using two aliases. They'll be accessed, for example, like this:
Version1::CompanyName.MyNamespace.MyClass
Version2::CompanyName.MyNamespace.MyClass
Also note that it's a good practice (to include global:: namespace) when you're generating code (for example all designers generated code) because you don't know in which scenario that code will be compiled (then collisions may occur).
Reasoning about :: and . well...it's not a question for SO (unless you're so lucky Eric is having some fun here on SO) but I may guess it's because they're different things. If same operator . is used then how can parser understand with global.System you want to use global namespace alias and not a class or namespace named global? They had to make global a reserved keyword and it won't solve the other problem of conflicting hierarchies...
This question already has answers here:
Importing nested namespaces automatically in C#
(7 answers)
Closed 9 years ago.
in c# if I want to add other System namespaces why do I need to call each namespace?
For example
if I want to call the System.Text namespace I have to use:
using System;
using System.Text;
why cant I just use using System?
Why do I also have to call using System.Text?
Why cant I use all System namespaces by just using System?
Why we use System for all namespace ?and what the meanings of system ?
the System namespace refers only to the files directly found under System. It does not automatically include all System.* namespaces. This is intended, since these are specialized namespaces which aren't needed in every class. Not every project automatically needs the System.Web namespace, for example.
You actually just need
using System.Text;
if you only want to use the System.Text namespace.
Within the System namespace, there are various types, eg System.DateTime. System.Text is not in System though, it is a separate namespace.
The confusion is caused by there being types at each "level" of a namespace. This means eg System.DateTime and System.Text both appear to be in System, when in reality the former is a type in System and the latter is a completely different namespace.
Here's a visual example that may help you out a little.
Basically, you can't access the namespace .Text from namespace .System because the methods contained within the .Text namespace do not exist in the .System namespace.
namespace OuterNamespace
{
public class DoStuff
{
public DoStuff()
{
//This DoStuff is different...
}
}
namespace InnerNamespace
{
public class DoStuff
{
public DoStuff()
{
//than this DoStuff.
}
}
}
}
public class Test
{
public Test()
{
//This "DoStuff" class
OuterNamespace.DoStuff outerStuff = new OuterNamespace.DoStuff();
//Is different than this "DoStuff" class
OuterNamespace.InnerNamespace.DoStuff innerStuff = new OuterNamespace.InnerNamespace.DoStuff();
}
}
Because they're different namespaces.
This article explains how to use Namespaces. Especially the example regarding Fully Qualified Names might be interesting to you.
System and System.Text are two different namespaces and that's why you had to refer both.
The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions
The System.Text namespaces contain types for character encoding and string manipulation. A child namespace enables you to process text using regular expressions.
Now if you are confused about naming style then I would stick to Microsoft naming convention since it clearly isolate relating types and easy to iterate. This make stepped type iteration than listing all CLR types within one System namespace.
More about namespaces
I have a solution with two projects. One namespace is MarketplaceWebServiceOrders and the other is MarketsplaceWebServiceOrders.Sample. I have public interface in the MarketplaceWebServiceOrders called MarketplaceWebServiceOrders. My main function is in MarketplaceWebServiceOrders.Sample and whenever I try to use the interface MarketplaceWebServiceOrders I get Error: MarketplaceWebServiceOrders.Samples.MarketplaceWebServiceOrders is namespace used use like a type.
I actually have this program compiled and running but I need to make changes and this popped up.
In this case you can access your interface specifying full name with namespace:
MarketplaceWebServiceOrders.MarketplaceWebServiceOrders instance = new ...();
Anyway, your naming looks wrong. You are probably misusing namespaces - they should "categorize" types, no need to have type name the same as namespace. Moreover, interfaces are prefixed with I letter by good convention.
You may want to consider refactoring your code to make the namespace and types a little less ambiguous. One of the purposes of namespaces is to organize code, so it's a bit redundant to have the same name in both the namespace and the type.
Well, the error states that you have an additional namespace level MarketplaceWebServiceOrders in the MarketplaceWebServiceOrders.Sample namespace. Is this true? If so, you will need to fully qualify the usage of the interface from the base namespace: MarketplaceWebServiceOrders.MarketplaceWebServiceOrders is the interface you say you want. Just don't use the base MarketplaceWebServiceOrders namespace in this code file.
To avoid this confusion if at all possible I would change the namespace name or the interface. The interface would be easier; add an "I" to the front of the identifier if it is an actual C# interface type (it's recommended naming convention in most C-style languages).
I am creating a little Math library for myself contained within a single project and am running into some issues with namespaces. I have the project MyMathLib and the top level namespace:
namespace MyMathLib
{ ... }
and in a separate file...
namespace MyMathLib.Addition
{ ... }
and...
namespace MyMathLib.Subtraction
{ ... }
In the MyMathLib.Subtraction namespace I have a method that needs to use a static method SomeClass.Work() defined in MyMathLib.Addition so I included using MyMathLib.Addition at the beginning of the Subtraction file. But when I try to use the method it would like me to first qualify it with Addition.SomeClass.Work() and I want to be able to just type SomeClass.Work(). What am I doing wrong?
Thanks!
EDIT
Thanks for the suggestions! In each file, I actually named the class after the namespace (i.e. in the namespace MyMathLib.Addition is a static class Addition and in MyMathLib.Subtraction there is a static class Subtraction). Apparently this is what caused the issue (looking back, I should have stated this instead of using SomeClass). If I change the namespace to MyMathLib.MyAddition while keeping the static class as Addition, the using MyMathLib.MyAddition works as I want; that is, I can now just type Addition.Work() in my static Subtraction class. I've seen classes named the same as it's containing namespace before, could someone maybe explain why this is causing an issue? Shouldn't the compiler be able to determine whether I want to use the namespace or the class from the context of the code?
I'm guessing that you either have two classes called SomeClass that are both in namespaces you reference, or you have a variable or property named SomeClass. Either of these situations would make it impossible for the compiler to know that you're trying to call the static MyMathLib.Addition.SomeClass.Work() method, but the specific solution the compiler is suggesting makes it seem more likely to be the former.
Update
Seeing your edit, that makes sense. If you were using these in a namespace outside of MyMathLib, then you would still be able to avoid this namespace conflict. However, because you are inside the MyMathLib.Subtraction namespace, the compiler will implicitly consider any portion of the namespace "above" you to take precedence over class names. In this case, when you say "Addition", the compiler will look for the following items to resolve the name:
A class explicitly identified by a using ... = ... directive.
MyMathLib.Subtraction.Addition namespace.
MyMathLib.Addition namespace.
Addition namespace.
Any classes in the namespaces identified by using statements.
In this case, you're hitting #3 before #4, so you should be able to work around it either by renaming the class or namespace, or by using Yahia's suggestion (#1):
using Addition = MyMathLib.Addition.Addition;
Update 2
After looking at the article you linked to, it sounds like the explicit using statement still won't work. I guess item #1 actually gets evaluated down around item #4 instead. Bummer. You can use an alias to give the class a different name locally:
using Add = MyMathLib.Addition.Addition;
...
var add = new Add();
But the best solution is still probably just to avoid the namespace collision entirely by changing your namespace or class name.
try putting additionally the floowing line into your substraction source
using SomeClass = Addition.SomeClass;
http://msdn.microsoft.com/en-us/library/dfb3cx8s.aspx
http://www.blackwasp.co.uk/NamespaceAliasQualifier.aspx
Sounds like you're in the Subtraction namespace...add this to the top, inside the namespace declaration:
using Addition;
That should do the trick.
I'm trying to design a class library for a particular engineering application and I'm trying to ensure that my class & namespace naming conventions make sense.
I have the following situation:
namespace Vehicle{
class Wheel{...} //base class for Wheel objects
class Engine{...} //base class for Engine objects
...
namespace Truck{
class Wheel: Vehicle.Wheel{...} //Truck specific Wheel object
class Engine: Vehicle.Engine{...} //Truck specific Engine object
...
}
namespace Car{
class Wheel: Vehicle.Wheel{...} //Car specific Wheel object
class Engine: Vehicle.Engine{...} //Car specific Engine object
...
}
...
}
The code gets used in ways that all of these classes will need to be referenced from within the same scope. The following situation would be likely:
...
Vehicle.Wheel.DoSomething();
Vehicle.Truck.Wheel.DoSomething();
Vehicle.Car.Wheel.DoSomething();
...
Under these circumstances, am I better off giving the classes more specific names
namespace Car{
class CarWheel: Vehicle.Wheel{...} //Car specific Wheel object
...
}
or leave the naming as shown in the first example and rely on the information that is encoded in the namespace for clarity? Under the latter approach, I assume I would want to utilize alaising for clarity in the code that makes use of this library, corret?
It seems redundent to have:
Vehicle.Car.CarWheel
or
Vehicle.Truck.TruckEngine
but I also want to have very descriptive and specific class names.
Philosophically, what I'm asking is whether or not to include the namespace as a part of the class name when considering if a class name is descriptive enough.
Typically namespaces are pluralized, so as not to collide with class names (e.g. it is likely you would want classes named Vehicle and Car) so I'd be inclined to use namespaces as follows:
namespace Vehicles;
namespace Vehicles.Cars;
namespace Vehicles.Trucks;
As for the names of classes, it would be typical to prefix the class name with the specialization, especially if they are likely to be used together, so you'd end up with something like:
class CarWheel : Wheel
class TruckWheel : Wheel
You can see this type of 'redundancy' everywhere in the .NET Framework, for example in the System.Xml namespace virtually all classes are prefixed with Xml, or in the System.Data.SqlClient namespace most classes are prefixed with Sql. It means that you can import namespaces with the using directive and then not have to fully-qualify class names throughout your code, e.g. which of the following is more readable?
Vehicles.Cars.Wheel wheel = new Vehicles.Cars.Wheel();
or
CarWheel wheel = new CarWheel();
It's obvious what both are doing, but the second is considerably shorter.
Note that if you do include the specialization in the name, then you may find that you don't need all the nested namespaces (.Cars, .Trucks, etc.) which can become painful if they are usually used together, and so every file using them would have to import all the namespaces, e.g.
using Vehicles;
using Vehicles.Cars;
using Vehicles.Trucks;
using Vehicles.SomethingElse;
using Vehicles.YetAnotherThing;
If you find this same stack of using directives is at the top of each file, then collapse the classes down into a single namespace. You typically include all related functionality that is expected to be used together in a single namespace, and only use nested ones for functionality that extends the base namespace but is less frequently used.
I would try to avoid reusing names across different namespaces, particularly if a client may want to use both in the same program.
Do you really need a namespace for Car, Truck etc? All these namespaces sound more like they ought to be classes than namespacese. Perhaps in your real situation it makes more sense though...