Tuesday, September 28, 2010

Getting Started with C# Console Application, how to write Hello world in C#?

To create and run a console application.

1. Start Visual Studio.
2. On the File menu, point to New, and then click Project.
3. In the Templates Categories pane, expand Visual C#, and then click Windows.
4. In the Templates pane, click Console Application.
5. Type a name for your project in the Name field.
6. Click OK.
The new project appears in Solution Explorer.
7. If Program.cs is not open in the Code Editor, right-click Program.cs in Solution Explorer and then click View Code.

The canonical “Hello, World” program can be written as follows.

using System;
namespace HelloWorld
class Hello
static void Main()
Console.WriteLine("Hello World!");

// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");

8. Press F5 to run the project. A Command Prompt window appears that contains the line Hello World!

The source for a C# program is typically stored in one or more text files with a file extension of .cs, as in hello.cs. Using the command-line compiler provided with visual Studio .NET, such a program can be compiled with the command line directive.

Csc hello .cs

Which produces an application named hello.exe. the output produced by this application when it is run is:
Hello World

Close examination of this program is illustrated:-
The using system: -Directive references a namespace called system that is provided by the Microsoft .NET Framework class library. This namespace contains the console class referred to in the Main method. Namespaces provide a hierarchical means of organizing the elements of one or more programs. A “using ” directive enables unqualified use of the types that are members of the namespace. The “Hello World” program uses Console.WriteLine.
The Main method: - is a member of the class Hello. It has the static modifier, and so it is a method on the class Hello rather than on instances of this class.
The entry point for an application: - the method that is called to begin execution –is always a static method named Main.
• The “Hello World” output is produced using a class library.

No comments:

Recent Posts