C Basic Syntax

C# Basic Syntax

You will learn a lot of C# syntax tricks as you progress through the book. This section introduces you to the most basic concepts required to create the simplest C# applicationthe canonical "Hello World" sample.

Code Blocks

As you know, all programming languages work on the same basic principle: individual instructions are executed in sequence to produce some result. Instructions can be anything from defining a class to printing information to the Console output.

In C#, multiple lines of code are grouped together into a logical execution block by wrapping the lines of code with the "curly brackets" or braces: the { and } symbols.

The Canonical "Hello World" Sample

It seems as though virtually every book on a programming language starts off with a program that prints the phrase "Hello World" to the console. Rather than risk horrible karma and unknown repercussions from breaking with tradition, I am going to inflict my own version of "Hello World" upon you.

To start, open up whatever 2005 IDE you have (C# Express 2005, or any of the Visual Studio 2005 editions) and create a new Console Application (make sure you select C# if you have multiple languages installed) called HelloWorld. Make sure that your code looks the same as the code shown in Listing 1.1.

Listing 1.1. The Hello World Application

using System; using System.Collections.Generic; using System.Text; namespace HelloWorld {   class Program   {     static void Main(string[] args)     {       Console.BackgroundColor = ConsoleColor.DarkBlue;       Console.ForegroundColor = ConsoleColor.White;       Console.WriteLine("---   Visual C# 2005 Unleashed   ---");       Console.BackgroundColor = ConsoleColor.Black;       Console.ForegroundColor = ConsoleColor.Yellow;       Console.Write("Hello ");       Console.ForegroundColor = ConsoleColor.Magenta;       Console.WriteLine("World");     }   } } 

The Console class (you'll learn about classes in Chapter 5, "Objects and Components") provides a set of methods for dealing with the console. In previous versions of .NET, you could not do anything with colors in the Console class. With .NET 2.0, you now have the ability to change the foreground and background colors of the console.

Press Ctrl+F5 or choose Debug and then Start without Debugging. Figure 1.2 shows the output of the application, including the newly added color features of the 2.0 Console.

Figure 1.2. The Hello World Application, in full color.

Microsoft Visual C# 2005 Unleashed
Microsoft Visual C# 2005 Unleashed
ISBN: 0672327767
EAN: 2147483647
Year: 2004
Pages: 298

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net