Saturday, October 17, 2009

C# Hello, World! Console App.

Pretty much every programmer learns "Hello, World!" first. Because C# is so much stronger and surprisingly different from C++ we are starting at the basics in my Advanced Programming class. Here is how you do a Hello, World! console application in C#.

First go into Visual Studio 2008/Express and goto File -> New -> Project. From the template list select "C# Console Application". In the name box go ahead and call the program "HelloWorld". Visual Studio will take it upon itself to generate code that looks something like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

Now this is a kinda overkill amount of code so we are going to just delete most of it. Remove most of the use lines as well as the namespace. Make sure you delete both the opening and closing curly braces for the name space. If you've done it right it should look like this.

using System;

class Program
{
    static void Main(string[] args)
    {

    }
}

Now we want to rename Program.cs in our file viewer. We want it called the same as our class which in this case is called "HelloWorld". Right Click on Program.cs and select Rename. Type in HelloWorld.cs . Don't forget the .cs which is obviously rather important! When you rename the file it will ask if you want to update references to the file within your code. Click YES.

Now all we have to do is add a console print command to the body of main. To do this type Console.WriteLine("Hello, World") ; into main. The code should now look like this.

using System;

class HelloWorld
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello, World!");
    }
}


With that your program should compile and run. If everything was done right then running it should look like this:


Congrats! Our program works!

- A. R. McGowan.
goodbye, world!

1 comment:

Post a Comment