Sunday, October 5, 2008

C# example for Beginners - Hello World

The simplest C# program is, of course, Hello World. You will need a C# compiler, which comes as a part of .Net Framework SDK. In your favorite text editor enter the following code:

class Hello
//This program displays Hello World
{
static public void Main()
{
System.Console.WriteLine("Hello World");
}
}

Save this file as myhello.cs and type

csc myhello.cs

If you haven't made any typos, something like:

Microsoft (R) Visual C# 2005 Compiler version 8.00.50727.42
for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727
Copyright (C) Microsoft Corporation 2001-2005. All rights reserved.

will appear in your command prompt window. The C# compiler will have created an executable code as a binary file in the PE format named myhello.exe. By simply typing myhello you will see

Hello World

class Hello
//This program displays Hello World
{
static public void Main()
{
System.Console.WriteLine("Hello World");
}
}

What does this simple C# program look like? Java! Note that all methods end with semicolons and Main() method is a part of class Hello. Statements are enclosed in braces. Like in Java and C/C++, every program has a Main() entry point. However, in Java the name of the program should be the same as the name of the class. There is no such restriction in C#.

System.Console is a namespace that takes care of console I/O (see exercise 5). Other methods of System.Console include Write method, which does not add a carriage return at the end of the line, and ReadLine, which gets user input from the console.

As the next step in learning C#, we will write a Windows program that displays "Hello World" dialog:

using System;
using System.Windows.Forms;
class Hello
{
static void Main()
{
MessageBox.Show("Hello World");
}
}

Running this code will produce the following dialog

Hello World dialog

0 comments: