Friday, November 27, 2009

Namespaces in C#

Namespaces in C#
A Namespace is simply a logical collection of related classes in C#. We bundle our related classes (like those
related with database activity) in some named collection calling it a namespace (e.g., DataActivity). As C# does
not allow two classes with the same name to be used in a program, the sole purpose of using namespaces is to
prevent name conflicts. This may happen when you have a large number of classes, as is the case in the Framework
Class Library (FCL). It is very much possible that our Connection Class in DataActivity conflicts with the
Connection Class of InternetActivity. To avoid this, these classes are made part of their respective namespace. So
the fully qualified name of these classes will be DataActivity.Connection and InternetActivity.Connection, hence
resolving any ambiguity for the compiler.
So, in the second line of our program we are declaring that the following classes (within { } block) are part of
MyHelloWorldApplication namespace.
namespace MyHelloWorldApplication
{
...
}
Printing on the Console
Console.WriteLine("Hello World");
Here we called WriteLine(), a static method of the Console class defined in the System namespace. This method
takes a string (enclosed in double quotes) as its parameter and prints it on the Console window.
C#, like other Object Oriented languages, uses the dot (.) operator to access the member variables (fields) and
methods of a class. Also, braces () are used to identify methods in the code and string literals are enclosed in double
quotation marks ("). Lastly, each statement in C# (like C, C++ and Java) ends with a semicolon (;), also called the
statement terminator.