Jump to content

C Sharp for Beginners/Hello World

From Wikibooks, open books for an open world

Here is your first C# program:

class HelloWorldProgram
{
    public static void Main()
    {
        System.Console.WriteLine("Hello, world!"); // prints some text on to the screen
        System.Console.ReadKey(); /* waits for the user
        to press a key
        */
    }
}

Let's go through each line and see what they do:

  • class HelloWorldProgram defines a class named "HelloWorldProgram". At this point, you can think of a class as a group of methods.
  • public static void Main() defines a method named "Main". A method is simply a code block (a container) containing some statements. The Main() method is special because it is the first thing that is run when your program is started.
  • System.Console.WriteLine("Hello, world!"); is a statement. A statement performs an action, which in this case is printing (outputting) "Hello, world!" to the screen.
  • System.Console.ReadKey(); is another statement. This time, it waits for the user to press a key.
  • After the last statement is executed, the program terminates.

Here's what should have happened:

  • You start the program.
  • The program outputs "Hello, world!" and waits.
  • You press a key.
  • The program closes.

Comments

[edit | edit source]

Comments are pieces of text which are ignored by the compiler. There are three types of comments, two of which were used in the hello world program above.

  1. A single line comment is produced by using a double slash (//) and tells the compiler to ignore the rest of the line.
  2. A multiline comment is started by using a slash and an asterisk (/*) and ended using an asterisk and a slash (*/). The compiler ignores everything in between, even if the comment stretches over multiple lines (hence the name).
  3. A documentation comment is used to document classes, properties, and methods. They start with three slashes (///) and use various XML tags.

Although comments are useful for describing code, they should not be used to simply restate what the code does, i.e.:

int number = 12; // declares a variable and assigns 12 to it

Console.WriteLine(number); // prints 12 to the console

Instead, they should be used to explain why a code does something that way.

int number = 12; // 12 is the number of months in a year.

Console.WriteLine(number);

There are other solutions to this, as you will see soon.