15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

382 ❘ ChaPTer 16 visuAl studiO 2010<br />

figure 16-8<br />

As you can see, you have a <strong>C#</strong> program that does not do anything yet but contains the basic items required<br />

in any <strong>C#</strong> executable program: a namespace <strong>and</strong> a class that contains the Main() method, which is<br />

the program’s entry point. (Strictly speaking, the namespace is not necessary, but it would be very bad<br />

programming practice not to declare one.) This code is all ready to compile <strong>and</strong> run, which you can do<br />

immediately by pressing the F5 key or by selecting the Debug menu <strong>and</strong> choosing Start. However, before<br />

you do that, add the following line of code — to make your application actually do something!<br />

static void Main(string[] args)<br />

{<br />

Console.WriteLine("Hello from all the authors of Professional <strong>C#</strong>");<br />

}<br />

If you compile <strong>and</strong> run the project, you will see a console window that stays onscreen barely long enough<br />

to read the message. The reason this happens is that Visual Studio, remembering the settings you specified<br />

when you created the project, arranged for it to be compiled <strong>and</strong> run as a console application. Windows<br />

then realizes that it has to run a console application but does not have a console window to run it from.<br />

Therefore, Windows creates a console window <strong>and</strong> runs the program. As soon as the program exits,<br />

Windows recognizes that it does not need the console window anymore <strong>and</strong> promptly removes it. That is all<br />

very logical but does not help you very much if you actually want to look at the output from your project!<br />

A good way to prevent this problem is to insert the following line just before the Main() method returns in<br />

your code:<br />

static void Main(string[] args)<br />

{<br />

Console.WriteLine("Hello from all the folks at Wrox Press");<br />

Console.ReadLine();<br />

}<br />

That way, your code will run, display its output, <strong>and</strong> come across the Console.ReadLine() statement, at<br />

which point it will wait for you to press the Return (or Enter) key before the program exits. This means that<br />

the console window will hang around until you press Return.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!