Hello World - Your First C# Program

Hello World: Your First C# Program

Crash Course

  • Start a new C# Console Application by going to File > New Project…, choosing the Console Application template, and giving your project a name.
  • Inside of the Main method, you can add code to write out stuff using a statement like Console.WriteLine("Hello World!");
  • Compile and run your program with F5 or Ctrl + F5
  • The template code includes code that does the following:
    • using statements pull in other chunks of previously written code (like #include in C++ or import in Java).
    • The namespace block puts all of the contained code in a single collection.
    • The code we are writing goes in the Program class, in a method called Main which the C# compiler recognizes as the start point for the application.

Introduction

In this tutorial, we'll make our very first C# program. Our first program needs to be one that simply prints out some variation of "Hello World!" or we'll make the programming gods mad. (It's tradition to make your first program print out a simple message like this, whenever you learn a new language. It is usually really simple, but yet still gives you enough to see the basics of how the programming language works. Also, it gives you a chance to compile and run your program, with very little chance for introducing bugs.)

So that's where we'll start—creating a new project and adding in the single line of code we need to write "Hello World". Once we've got that, we'll compile and run it, and you'll have your very first program!

After that, we'll take a minute and look at the code that you have written for your program in more detail, before moving on to slightly more difficult, but infinitely more awesome stuff in the future tutorials.

Creating a New Project

OK, let's get started with our first C# program! Open up Microsoft Visual Studio.

When the program first opens, you will see the Start Page come up. To create a new project, you can either select the "New Project…" button on the Start Page, or you can go up to the menu and choose File > New Project… from the menu bar. The "New Project…" button is shown below:

StartPage-NewProject.png

Once you have done this, a dialog will appear, asking you to specify a type of project and a name for the project. This dialog is shown below:

ProjectSetup.png

On the left side, you will see a few categories of templates to choose from. (If you have already installed XNA Game Studio, there will be additional options, and if you are using the full Visual Studio, there will be lots more options for other programming languages.) Click on the category that says Visual C#.

Then, in the list in the center at the top, find and select the Console Application template. The Console Application template is the simplest template and it is exactly where we want to start. (OK, there's an Empty Project template that is completely empty, but the Console Application is the template that is the simplest that actually has some stuff in it.) For all of the stuff we will be doing in the C# Crash Course, this is the template we'll be using. If you start doing a bunch of Windows GUI applications (with all of the buttons and dialog boxes and stuff) you'll use the other templates, and when we get to other tutorial sets about making XNA games, we'll use other templates as well.

At the bottom, type in a name for your project. I've called mine "HelloWorld". Your project will be saved in a directory with this name so you can find it later. It doesn't really matter what you call a project, but you want to name it something intelligent, so you can find it later, when you are looking at a list of all of your projects. If all of your projects are "ConsoleApplication1", "ConsoleApplication2", and "ConsoleApplication3", you'll never remember what you did in each project, so pick a helpful name.

Finally, press the OK button to create your project! (This may take a few seconds for it to get everything set up for you….)

A Real Brief Tour of Visual Studio

Once your project has loaded, it is worth at least a real brief discussion of what you see before you. For starters, what you see should look something like the image below:

VisualCSharpExpressTour.png

It may not look exactly identical, depending on what settings you have set up, but it should look pretty close. In the image above, on the left side is the Toolbox, which you can ignore for now.

In the center should be some text that starts out with using System;. This is your program's source code! It is what you'll be working on. We'll discuss what it means and how to modify it in a second.

On the right side is the Project Explorer. This shows you a big outline of all of the files you have in your project, including the main one that we'll be working with, which is called "Program.cs". The *.cs file extension means it is a text file that contains C# code. If you double click on any item in the Project Explorer, it will open it up in the main editor window.

On the bottom is the Error List. If you make a mistake when writing your C# code, and the computer doesn't know what it means, it will show you the error in a list down here, and tell you where it is, and what's wrong with it, so you can fix it.

On the bottom right, you might see the Properties Window, which shows the properties of a selected file or item. We don't need to worry about this too much right now.

If, by chance, you are missing a window that you feel like you want, you can always open it up by going to View > Other Windows and choosing the window you want to see. For right now, though, if you have the main editor window open with your Program.cs file in it, and the Project Explorer, you should be good to go.

Saving your Project

It's kind of weird, but for some reason, your project isn't automatically saved yet, at the starting point. In fact, you can make all sorts of changes and compile and run your program, and then if your computer crashes, you may lose all of the changes you've made.

I'm bringing this up because I've learned this the hard way. I once spent several days on a program, editing, compiling, running, and repeating. After several days of work, my computer crashed, and even though I had saved the individual files, they had been saved in a temporary directory, and I lost it all.

(There's another way to do this, if you dig around in the settings, but this is the easiest for now.)

So right now is a great time to save your project. To do this, go up to the menu and choose File > Save All. You will see the dialog below, which allows you to choose a name for your project and a directory. I usually just leave it in the default "Projects" directory..

SaveDialog.png

Modifying Your Project

So in the center, you should currently see some text that looks identical to this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

In a minute, we'll discuss what all of that does, but for now, let's go ahead and make our first change—something that will print out the message "Hello World!".

Right in the middle of that code, you'll see three lines that say static void Main(string[] args) then a starting curly brace ('{') and a closing curly brace ('}'). We want to add our new code right between the two curly braces.

Here's the line we want to add:

Console.WriteLine("Hello World!");

So now our program's full code should look like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

We've completed our first C# program! Easy, huh?

Compiling and Running Your Project

Remember, though, that your computer doesn't magically understand what you've written. It understands special instructions that are composed of 1's and 0's called binary. Fortunately for us, a part of Visual Studio is a thing called a compiler. A compiler will take the C# code that we've written and turn it into binary that the computer understands.

So our next step is to compile our code (it's really easy!) and run it.

We're going to start by compiling and running our program.

To start this process, press F5 or choose Debug > Start Debugging from the menu.

This runs your program in debug mode, which means that if something happens while your program is running, it won't simply crash, but rather, Visual Studio will handle it, and stop in the middle of your program, and show you the problem that you are having, allowing you to debug it.

So there you have it! You've made a program, compiled it, and executed it!

If it doesn't compile and execute, double-check to make sure your code looks like the code above.

Help! My program is running, but disappearing before I can even see what it did!

I'm sure you just ran into this problem when you executed your program. You push F5 and the program runs, a little black console window pops up, but only for a split second, and then it goes away, and you have no clue what happened.

There's a good reason for that. Your program ran out of things to do, and so it finished and closed on its own.

But we're really going to want a way to make it so that doesn't happen. There's two solutions to this, each of which has its own strengths and weaknesses.

Approach #1: When you run it without debugging, it will actually always pause before closing. So we can run it without debugging. You can do this by choosing Debug > Start Without Debugging in the menu or by pressing Ctrl + F5. Do this now, and you'll see that it prints out your "Hello World!" message, plus another message that says "Press any key to continue…", which does exactly what it says, and waits for you before closing the program.

But there's a distinct disadvantage to doing this. We're no longer running in debug mode, and so if something happens with your program while it is running, your application will crash and die (hey, just like all of the other "cool" programs out there!). Which brings us to an alternative approach:

Approach #2: Put another line of code in that makes the program wait before closing the program. You can do this by simply adding in the following line of code, right below where you put the Console.WriteLine("Hello World!"); statement:

Console.ReadKey();

So your full code, if you use this approach, would look like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Console.ReadKey();
        }
    }
}

Now, that's one more line of code that you have to add to your program (in fact, every console app you make), which can be a little annoying. But at least you can still run your program in debug mode, which you will soon discover is a really nice feature.

The bottom line, here, though, is that this is only going to be a problem when you write console apps. So for the rest of this set of tutorials. Before long, you'll be making windows apps or XNA games, and this won't be a problem. They work in a slightly different way, and this won't come up as an issue.

A Closer Look at Your Program

Now that we've got our program running, let's take a minute and look at each of the lines of code in the program we've got. I'll try to explain what each one does, so that you'll have a basic understanding of everything that you've got in your simple "Hello World" program.

Using Statements

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

The first few lines of your program all start with the keyword "using". A keyword is simply a reserved word, or a magic word that is a built-in part of the C# programming language. It has special meaning to the C# compiler, which it uses to do something special. The using keyword tells the compiler that there is a whole other pile of code that someone else has written (in our current case, it was written by the guys over at Microsoft) that we want to be able to access.

So when you see something that looks like this: using System;, you know that there is a whole pile of code out there, that is called "System", which our code will want to use. Without this line, the C# compiler won't know where to find certain things, and won't be able to run your program. You can see that there are four using statements in your little program that are added by default. We can leave these exactly the way they are for the near future.

A Brief Introduction to Namespaces

As I just mentioned above, while discussing using statements, people, including yourself, can create huge piles or collections of code that are all related to each other. To manage these piles of code better, related code is usually put into groups called namespaces. There's a good reason for that particular name, but it is a discussion for another day.

You can see that in your program, just after the using statements, that the next thing is this:

namespace HelloWorld
{

In C#, the curly braces are used to start and end sections of related code called a "code block". You'll see them come up in several places as we learn C#. Every starting curly brace ('{') will have a matching ending curly brace ('}') later on, and so we see in our program that the last line of the program is the end of the namespace code block which looks like this:

}

This line of code tells us that everything in between the two curly braces belongs in the namespace "HelloWorld". namespace is a keyword, which is what gives the line specific meaning, but the "HelloWorld" part is arbitrary. You could call it anything else, and it would still work. Visual Studio used HelloWorld because that was the name of your program.

The Class and Method Declarations

The next part of the code is the class and method declarations. We're going to be talking about classes and methods lots, lots more before too long, but for now, we only really need a basic understanding of them.

Here's the part I'm referring to:

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

and then later, to close it…

        }
    }

At a basic level, a class is usually thought of as a "blueprint", or design for a particular kind of object. We'll look at this in more detail later, but most of the code you write will belong to a particular class. In this case, the name of the class is the "Program" class. We'll be making all sorts of classes as time goes along. Classes are a critical part of "object-oriented" programming languages like C# and Java.

Inside of that, you have "methods" (sometimes called functions, procedures, or subroutines in other programming languages) that is a block of code that performs a specific task. Again, we'll be talking about methods in a lot more detail later. For now, the important thing to remember is that the C# compiler is going to be looking for a method called "Main".

The rest of the stuff on that line (static, void, the parentheses ( and ), and the string[] args form what it called the "method signature" and defines certain properties about the method. These pieces are also critical for the C# compiler to find your "main" method where the program will start, so don't modify them.

We'll discuss what each of these things mean later on, in future tutorials. For now, the important thing is that you know that the C# compiler is looking for this specific line in your code to use as the starting point of your program.

Anything you put inside of the Main method will get ran by the computer, and for the next few tutorials, everything we do will be right in here.

What's Next?

Whew. That was kind of a long tutorial, I know. And we haven't even gotten a whole lot done yet. Just writing out some simple text.

That's OK, though. We have to start somewhere, and this is where everyone starts.

Before taking our first huge step into the world of programming, we'll first take a small pit stop, and take a look at a very important feature of the C# language (and also of virtually every other programming language out there) called comments. This will show us how to make notes for ourselves and other programmers about what the program is supposed to do.