Hi Guys
NP127 namespace confusion
Name namespace is used in two occasions. One is when we are indicating following using statements we use the word namespace.
using System;
using System.Windows.Forms;
Other occasion is classes can be enclosed in the namespace in following way.
namespace XXXXXXXX
{
}
What is the reason for that? Please explain.
Thank you
Posted Aug 17, 2008, 9:57 AM
Thank you very much for your explanation.
AlanPosted Aug 17, 2008, 9:20 AM
Well, the 'using' directive provides access to all the types in a namespace without having to fully qualify them by preceding them with the namespace name.
So if you have this line:
using System.Windows.Forms;
then you can use all the types in that namespace without further ado, i.e.
'Form' rather than System.Windows.Forms.Form
'Button' rather than System.Windows.Forms.Button
and so on.
You may be wondering why the Visual Studio designer adds the 'using' directive to all Windows Forms applications but then still uses the fully qualified names in the generated code.
The reason for this is that the designer can't be sure that you won't import some other namespace that uses the same names for its types though, in my experience, this would be unusual.
Posted Aug 17, 2008, 7:40 AM
So even though 'using' directives do different function they can be called namespace. The following paragraph is in a book.
For example:
Including the statement to use the System.Windows.Forms namespace provides you with access to many Form features in addition to the MessageBox. You will use many of these features as you work through the exercises in the next few chapters.
AlanPosted Aug 17, 2008, 6:13 AM
Namespaces are a way of organizing your types to avoid clashes between similarly named types in other namespaces which you import into your program. So if you have this:
namespace Maha
{
public class Foo{}
}
and you import another namespace 'Alan' say which also has a Foo class, then you can always distinguish between the two by using their 'fully qualified names' i.e:
Maha.Foo mf = new Maha.Foo();
Alan.Foo af = new Alan.Foo();
You can't just do this:
Foo f = new Foo();
because the compiler wouldn't know which Foo you were referring to.
'using' directives, on the other hand, save you the bother of having to use fully qualified names for types where there are no clashes. So, if you hadn't imported the 'Alan' namespace, you could do this:
using Maha;
namespace SomeOtherNamespace
{
public class Goo
{
public Foo foo; // this can only now refer to Maha.Foo
}
}
So 'using' directives are simply a way of saving typing and making your program easier to read.