Prerequisites For .NET Programming - Namespaces
(Page 3 of 4 )
As with C++, namespaces are a vital part of .NET languages. You can think of a namespace as a "virtual container" for classes, functions and variables, which encapsulates them into a uniquely identifiable region. Namespaces separate variables into physical scopes, which reduces variable naming ambiguities. The pseudo code for a namespace is shown below:
Namespace ns1
{
variable x
Namespace ns2
{
variable y
}
}As you can see, namespaces are hierarchical, meaning that several namespaces can be declared (and used) within a "parent" namespace. To refer to a nested namespace, you need to reference it using its parent Id first, followed by the dot operator ".", and then its actual namespace name.
For example, if you wanted to refer to the "sqlConnection" class in the "Data" level two namespace (second in the hierarchy) to create a new instance of that object, then you would do so like this:
System.Data.sqlConnection myConn = new System.Data.sqlConnection();See how the dot operator separates each new namespace hierarchy? If we ran this line of C# code, then the "myConn" object would now contain a new instance of the System.Data.sqlConnection class.
Here is a simple example of using namespaces in both VB.NET and C#:
VB.NET:Namespace Computer
Class IBM
'Class methods go here
End Class
End NamespaceC#:namespace Computer
{
class IBM
{
// Class methods go here
}
}As mentioned above, namespaces can be arranged in a hierarchical format. We can create nested namespaces in both VB.NET and C#:
VB.NET:Namespace Computer
Namespace Desktop
Class IBM
'Class methods go here
End Class
End Namespace
Namespace Server
Class MainFrame
Public Function ShowMainFrame
'Code for function goes here
End Function
End Class
End Namespace
End NamespaceC#:namespace Computer
{
namespace Desktop
{
class IBM
{
// Class methods go here
}
}
namespace Server
{
class MainFrame
{
public void ShowMainFrame()
{
// Code for function goes here
}
}
}
}Namespaces are very simple to create in both VB.NET and C#. In VB.NET, we use the "Namespace
namespace_name ... End Namespace" syntax, while in C#, we use the "namespace
namespace_name {}" syntax. As you'll see in future articles, all classes in both VB.NET and C# are encapsulated into namespaces.
Next: Conclusion >>
More ASP.NET Articles
More By James Yang