C# programs are organized using namespaces. Namespaces are used both as an "internal" organization system for a program, and as an "external" organization system – a way of presenting program elements that are exposed to other programs.
Earlier, we presented a "Hello, world" program. We’ll now rewrite this program in two pieces: a HelloMessage
component that provides messages and a console application that displays messages.
First, we’ll provide a HelloMessage
class in a namespace. What should we call this namespace? By convention, developers put all of their classes in a namespace that represents their company or organization. We’ll put our class in a namespace named Microsoft.CSharp.Introduction
.
namespace Microsoft.CSharp.Introduction { public class HelloMessage { public string GetMessage() { return "Hello, world"; } } }
Namespaces are hierarchical, and the name Microsoft.CSharp.Introduction
is actually shorthand for defining a namespace named Microsoft
that contains a namespace named CSharp
that itself contains a namespace named Introduction
, as in:
namespace Microsoft { namespace CSharp { namespace Introduction {....} } }
Next, we’ll write a console application that uses the HelloMessage
class. We could just use the fully qualified name for the class – Microsoft.CSharp.Introduction.HelloMessage
– but this name is quite long and unwieldy. An easier way is to use a "using" directive, which makes it possible to use all of the types in a namespace without qualification.
using Microsoft.CSharp.Introduction; class Hello { static void Main() { HelloMessage m = new HelloMessage(); System.Console.WriteLine(m.GetMessage()); } }
Note that the two occurrences of HelloMessage
are shorthand for Microsoft.CSharp.Introduction.HelloMessage
.
C# also enables the definition and use of aliases. Such aliases can be useful in situation in which name collisions occur between two libraries, or when a small number of types from a much larger namespace are being used. Our example can be rewritten using aliases as:
using MessageSource = Microsoft.CSharp.Introduction.HelloMessage; class Hello { static void Main() { MessageSource m = new MessageSource(); System.Console.WriteLine(m.GetMessage()); } }