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 |
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
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

Finally, we will write a Web application that displays "Hello World" in the browser window:
<%@ Page language="C#" %>
<html>
<head>
<title>
Hello C#
</title>
</head>
<body>
<p><% Response.Write("Hello World");%></p>
</body>
</html>
This code needs to be saved as a file with an aspx extension (e.g. helloWeb.aspx) and placed in a virtual folder (e.g. c:\inetpub\wwwroot). To run this code, type the URL pointing to the file in the browser (e.g http://localhost/helloWeb.aspx)
Exercise
Write a routine that asks a user some questions and gives meaningful output based on her answers.