Page 13 - DCAP505_MODERN_PROGRAMMING_TOOLS_AND_TECHNIQUES_II
P. 13
Unit 1: Introduction to C#
Consistency Notes
C# unifies the type system by letting you view every type in the language as an object. Whether
you’re using a class, a struct, an array, or a primitive, you’ll be able to treat it as an object. Objects
are combined into namespaces, which allow you to access everything programmatically. This
means that instead of putting includes in your file like this
#include <stdlib.h>
#include <studio.h>
#include <string.h>
You include a particular namespace in your program to gain access to the classes and objects
contained within it as:
using System;
In COM+, all classes exist within a single hierarchical namespace. In C#, the using statement lets
you avoid having to specify the fully qualified name when you use a class.
Example: The System namespace contains several classes, including Console.
Console has a WriteLine method that, as you might expect, writes a line to the system console. If
you want to write the output part of a Hello World program in C#, you can say:
System.Console.WriteLine(“Hello World!”);
This same code can be written as:
Using System;
Console.WriteLine(“Hello World!”);
That’s almost everything you need for the C# Hello World program. A complete C# program
needs a class definition and a Main function. A complete, console-based Hello World program
in C# looks like:
using System;
class HelloWorld
{
public static int Main(String[] args)
{
Console.WriteLine(“Hello, World!”);
return 0;
}
}
The first line makes System – the COM+ base class namespace – available to the program. The
program class itself is named HelloWorld (code is arranged into classes, not by files). The Main
method (which takes arguments) is defined within HelloWorld. The COM+ Console class writes
the friendly message, and the program is finished.
One final point about classes. If you have classes with the same name in more than one namespace,
C# lets you define aliases for any of them so you don’t have to fully qualify them. Suppose you
have created a class NS1.NS2. ClassA that looks like this:
namespace NS1.NS2
{
LOVELY PROFESSIONAL UNIVERSITY 7