Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » C# Language » Working with Namespaces in C#

Working with Namespaces in C#

In C#, namespaces are used to logically arrange classes, structs, interfaces, enums and delegates. The namespaces in C# can be nested. That means one namespace can contain other namespaces also.

Author Rank :
Page Views : 36909
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
DevExpress Free UI Controls
Become a Sponsor
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

In C#, namespaces are used to logically arrange classes, structs, interfaces, enums and delegates. The namespaces in C# can be nested. That means one namespace can contain other namespaces also. The .NET framework already contains number of standard namespaces like System, System.Net, System.IO etc. In addition to these standard namespaces the user can define their own namespaces. 

Declaring a Namespace 

The C# language provide a keyword namespace to create a user defined name space. The general form of declaring a namespace is as follows.

namespace <namespace_name>
{
// Classes and/or structs and/or enums etc.
}

Where namespace is the required keyword. The name of namespace can be any valid C# identifier or combinations of identifiers separated by commas.

For example:

using System;
namespace Rajesh.Csharp.Codes
{
class MyClass
{
public MyClass()
{
Console.WriteLine("My Class");
}
}
class MyClient
{
public static void Main()
{
MyClass mc =
new MyClass();// Displays 'My Class'
}
}
}

It is not possible to use any access specifiers like private, public etc with a namespace declarations. The namespaces in C# are implicitly have public access and this is not modifiable. 

The namespace elements can't be explicitly declared as private or protected. The namespace allows only public and internal elements as it members. The default is internal.

The following code doesn't compile in C#, since the class inside the namespace is declared as private.

namespace Rajesh.Csharp.Codes
{
private class MyClass
{
}
}

Accessing Namespace Members 

The namespace members can be accessed by using a fully qualified name, which including the namespace name and member name separated by dot(.) from outside the namespace. For example 

using System;
namespace Rajesh.Csharp.Codes
{
class MyClass
{
public MyClass()
{
Console.WriteLine("My Class");
}
}
}
class MyClient
{
public static void Main()
{
//Using the fully qualified name to access the namespace member.
Rajesh.Csharp.Codes.MyClass mc = new Rajesh.Csharp.Codes.MyClass();
}
}

But in order to save developer from typing fully qualified name every time, the C# provides another keyword using to define some aliases to namespaces. Then while writing our code, we just refer the classes with their class name only. During compile time, the compiler will map all the class names with aliases to reach at the fully qualified name of the class. Once the fully qualified name has been found, it is used to convert the code to IL code. Remember that in IL code all classes, interfaces, enums and delegates are referenced with their fully qualified name.

An example of using is shown below. 

using
Rajesh.Csharp.Codes;
MyClass mc =
new MyClass();

Remember that inside C# namespaces, it is possible to use the keyword using.

namespace MyNameSpace
{
using System;
class MyClass
{
}
}

Any code contained within namespace MyNameSpace has access to System namespace without fully qualifying the type names, but those types are not members of the MyNameSpace namespace. 

The same namespace can be span over multiple lines as follows. 

using System;
namespace Rajesh.Csharp.Codes
{
class MyClass
{
public MyClass()
{
Console.WriteLine("My Class");
}
}

namespace Rajesh.Csharp.Codes
{
class MyClient
{
public static void Main()
{
MyClass mc =
new MyClass();
}
}
}

Nesting Namespaces 

In C#, namespaces can be nested with each other as showing below.

using System;
namespace Outer
{
namespace Inner
{
class MyClass
{
public MyClass()
{
Console.WriteLine("My Class");
}
}
}
}
class MyClient
{
public static void Main()
{
Outer.Inner.MyClass mc =
new Outer.Inner.MyClass();
}
}

Creating Aliases 

With the help of the keyword using, it is possible to create an alias name for a namespace or type. For example 
using con = System.Console; // Create an alias
class MyClient
{
public static void Main()
{
con.WriteLine("Hey rajesh! how you");
}
}

Standard Namespaces in .NET 

The following are some of the standard namespaces in .NET framework.

  • System: Contain classes that implement basic functionalities like mathematical operations, data conversions etc.
  • System.IO: Contains classes used for file I/O operations.
  • System.Net: Contains class wrappers around underlying network protocols.
  • System.Collections: Contains classes that implement collections of objects such as lists, hashtable etc.
  • System.Data: Contains classes that make up ADO.NET data access architecture.
  • System,Drawing: Contains classes that implement GUI functionalities.
  • System.Threading: Contains classes that are used for multithreading programming.
  • System.Web: Classes that implement HTTP protocol to access web pages.
  • System.Xml: Classes that are used for processing XML data.

These are some of impoetant namespaces of .NET framework. Remember that the above list is a not complete one.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Rajesh VS
Rajesh V.S is a software engineer in the area of C/C++/JAVA for the last 5 years. Currently he is interested in core C# language. He is Sun Certified Java Programmer. His other area of interest includes Design Patterns and CORBA. He is also a writer of numerous articles for many technical Web sites.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
Become a Sponsor
 Comments
Security problem that keeps going back to namespace by Derek On October 9, 2008
Hey there, I have a difficult security architecture issue I was hoping your namespace fluence could help. I have a public class exposed through a remoting service with a Singleton activation model. All calls to this service requires a sessionid used as a key. Most service functionality is in the session object, which calls are proxied to by the main service class by taking function calls to it and using the sessionid to pull a session instance from a dictionary and calling the same function without sessionid on the session instance. The security works very nicely for my 3 tier architecture. My problem is that I recently have began to use strongly typed datasets that I wish to allow client caching and fast and easy updates through the service. Using the tutorial and video offered by msdn here http://msdn.microsoft.com/en-us/library/bb384570.aspx the structure that ends up being designed and rapidly generated has the data adapters available for my wcf service to instantiate and then directly call without the safety of session encapsulation. The generated code makes all the data adapter functions, such as "GetOrders" as public functions of the generated data adapters, which in turn are public/global objects of the namespace you put them in. Is there any way without mutilating the generated code such that it no longer works with the designer that I can encapsulate these functions without having to literally copy each query function individually and create a copy of it within my service class that appropriately checks for session validation? To express my problem using the example provided in the tutorial, you have a WCF service, which is a proxy in my architecture, that would have a function like this in my proxying WCF Service: public ReferenceDataEntity.dbDataSet.HappyDataTable GetTable() { RemoteServiceClass.dbDataSetTableAdapters.HappyTableAdapter daHappy = new RemoteServiceClass.dbDataSetTableAdapters.HappyTableAdapter(); return daHappy.GetTable(); } In order to secure this, the only way I can see it in my architecture would be to change this function as follows to make it like the rest of my functions in this service: public ReferenceDataEntity.dbDataSet.HappyDataTable GetTable() { Return RemoteServiceClass.GetTable(sSessionID); } … and then have to add to my RemoteServiceClass the following type of function: public ReferenceDataEntity.dbDataSet.HappyDataTable GetTable(string sSessionID) { If(dictionarySessions.ContainsKey(sSessionID)) { RemoteServiceClass.dbDataSetTableAdapters.HappyTableAdapter daHappy = new RemoteServiceClass.dbDataSetTableAdapters.HappyTableAdapter(); return daHappy.GetTable(); } } ... Most of our code in fact is within the session objects themselves in the dictionary and is futher encapsulated/called in them. Of course, the idea of writing all of this proxying for each and every generated query function becomes quickly infeasible. If I could only encapsulate the namespace it puts the generated code into some how or something it would be so much easier. Is there a secure way of using an interface or anything to encapsulate the namespace functionality for session validation without going through this? Thanks for any help
Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.