Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
World Class ASP.NET Hosting – Click Here for 3 Months Free/NO Setup Fee!
 Resources  
Close
 Our Network  
Close
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:
Total page views :  30694
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor

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.


Login to add your contents and source code to 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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
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 | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.