14 min read

Hello World: Your First C# Program

Crash Course

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.

A “Hello World” program is traditional because it is small enough to avoid most human errors, and is enough to ensure that all of your tools are set up and working correctly.

We will create the program from a template, which will actually start with this simple “Hello World” program. We’ll then compile and run our program to see it in action.

After that, we’ll make a couple of tweaks to it to begin exploring how it works. We’ll also pick apart the code generated from the template, to start understanding what all its parts do.

Creating a New Project

Let’s start by opening Visual Studio, if you don’t have it open already.

On the launch page, you can click on the button on the bottom left labeled Create a new project.

Visual Studio launch page

If you are already in the Visual Studio editor and don’t see the launch page, you can also create a new project by choosing File > New Project… from the menu bar. This will take you to the next page, where you can pick a project from one of the templates.

Create a new project page

The list of available templates will change based on what plugins and workflows you chose when running the installer.

For this tutorial set, the template you want is called Console Application. Depending on what you have installed, there are a few similar ones, including one called Console App (.NET Framework) and another one called Console Application (the same name as the one we want!), but that is for Visual Basic. To ensure you get the right one, you might want to choose C# from the languages drop down and Console from the project types drop down. The Visual Basic (VB) one is the wrong language, and the .NET Framework one is tied to a mostly-outdated way of doing C#.

caution

Pay attention to the template you choose on the screen above! Getting the wrong one leads to things not working like you’d expect.

After finding the template, you can push Next to move on to the next screen, where you can pick a project name and location to save your code.

Configure your new project page

Give your project a good name. You’ll never remember what “ConsoleApp14” did two months later. I’ve named mine “HelloWorld”.

You may also want to note (and possibly change) the location. You may want to be able to find it on your file system later. (Though it can always be looked up later.)

There is a checkbox at the bottom labeled Place solution and project in the same directory. Whether this is checked or not doesn’t have a huge impact on things, but I usually check it for small programs and uncheck it if I know I’m building something large that will need to be broken down into multiple projects (high-level components). Either way is fine, but I’d recommend checking the box for any projects you make while doing this tutorial set, but it won’t really impact anything we do here, if you don’t.

Press Next to continue to the next page.

Additional information page

On this final page, you can pick your target framework. For this tutorial set, you’ll want to pick .NET 5.0 or newer.

Press Create to have Visual Studio create the new project.

An Overview of Visual Studio

Once your project loads, you will get your first view of the Visual Studio IDE. Let’s take a moment and discuss what we’re seeing.

Overview of the Visual Studio IDE

Keep in mind that nearly everything is configurable, and things will vary depending on what is installed. So if your version doesn’t look quite like the picture, that isn’t a problem. (If you really mess up the layout, you can always reset it through Window > Reset Window Layout.)

  1. Main Menu. Visual Studio has a menu, like most other desktop software. Virtually every command in the system can be accessed through something on the menu, and it is worth taking a moment to look through the menu options to get a flavor of what’s there.
  2. Code Editor. The main, open area is the code editor. You will spend 95% of your time in this part of Visual Studio. This is where you will type your C# code.
  3. Solution Explorer. The solution explorer gives you a high-level view of all of the code and configuration that goes into your entire C# program. By double-clicking on items in the Solution Explorer, you can open them in the code editor. You will spend 4% of your time in this part of visual studio.
  4. Properties Window. This window shows you details of whatever you have selected in other windows. Click on the different items in the Solution Explorer to see how this changes.
  5. Error List. This window shows you the problems in your code. This window is off, by default, until you actually have some errors in your program, so you may not see it initially.
  6. Toolbar. Visual Studio has many toolbars that you can open, but the standard toolbar is the one that is open by default. It contains a lot of buttons for common operations, including saving, undo and redo. In the middle of this toolbar are two drop downs and a green arrow button, which are used to run your program. We’ll be using this soon (and often).

Most of Visual Studio’s screen space is filled with windows, including the Solution Explorer, Properties, and Error List windows described above. You can resize and rearrange these to your heart’s content. You can also close them out, and open others. The View menu has a lot of views contained inside it (click on any to open them) and several other top-level menus have their own set of windows as well. We won’t cover them all here, but you can explore the ones you find interesting.

Running Your Program

The template we chose created a basic “Hello World” program. We don’t even have to modify anything!

Let’s run our program and see it live before we dig into what any of the code means.

To run your program, press the Start button (green arrow icon) at the top of the window in the toolbar:

Start button

You can also press F5 , if you prefer keyboard shortcuts. (That one is good to know, because you’ll use it a ton.)

If all goes well, you’ll see your program, produced from the template, running in a new console window:

Hello World program output

Congratulations! You’ve made your first C# program!

The first line in that window is the text our program was supposed to display.

The rest is just the window telling you that the program completed and was successful. You can ignore that for now. (If you just opened and ran your program outside of Visual Studio, it would not have anything but the first line. All of that is not really part of your actual program, but just a part of how Visual Studio runs your program.)

Modifying Your Program

Before we get into the details of how this program actually works, modifying it to do a little something else is pretty simple.

You should be able to see your code in the editor. Look and make sure you see text that you can edit that looks like this:

using System;

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

As you can imagine, the text in the middle of the program that says "Hello World!" is what is displayed. You can modify that text and change what it says.

Before continuing on, try the following two things:

  1. Change the text to say, “Greetings, Earthling!” (or some alternative greeting of your own choice) and run the program again.
  2. See if you can modify the program to display three lines of text: "You have my sword.", "And my bow.", and "And my axe!". Run the program again.

My solution to the second challenge is below:

using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("You have my sword.");
            Console.WriteLine("And my bow.");
            Console.WriteLine("And my axe!");
        }
    }
}

How the Code Is Structured

caution

Don’t skip the rest of this tutorial, just because it is mostly descriptive text! The following sections point out the fundamental concepts of a C# program. Read it carefully.

C# is often used for rather large programs–ones thousands or millions of lines long. As you can imagine, very large programs can be hard to manage.

There are quite a few tools in the C# language to help you organize your code. The whole program is broken into chunks. The chunks are broken into smaller chunks. The smaller chunks are broken into even smaller chunks.

Much of what you see in the code that came out of the template is code that is designed to help you structure your code. In fact, most of the time, when you set a set of curly braces ({ and }), you can think of it as defining or identifying an organizational chunk in your code. Everything inside the curly braces is its contents or “children.” Officially, things that belong inside or are part of another thing are called members of its container.

“Member.” That’s a good word to remember. You’ll see it come up all over the place.

Namespaces, classes, and methods are all different ways to group code. The template code has one of each of those.

Many elements in code are given names. The computer doesn’t really care what these names are. They’re meant for you and other people, so that you can remember what the thing is and what it does. C# refers to these names as identifiers . You’ll see that word a lot, too. But “identifier” is just a fancy word for “name.”

The template code has a namespace called HelloWorld. That was chosen to match the name of your project and solution.

A namespace can be thought of as a grouping of other code elements that are closely-enough related to share a common name. In some ways, you could think of this like a surname or like the houses in Harry Potter. (You might say Harry belongs to the Gryffindor namespace.)

By the way, see how in your code, certain words appear blue? Certain words are special words that the computer uses to give your code meaning, and to know what your intent is. These special words are called keywords . You can see several of these, including namespace, class, static, and void.

The template code has a class called Program. Because Program is defined inside of the HelloWorld namespace, it is a member of that namespace. Classes are extremely powerful concepts, but also a bit complex. They’re chunks of code that are designed to perform one job in the overall system. For the next several tutorials, we’ll only have one class, and it will generally always be called the Program class, because that is what the template names it. Its one job is “run the program.”

Eventually, we’ll get into how you define other classes and make them work together.

There isn’t a keyword for a method, but the line that says, static void Main(string[] args) defines a method . Methods are a section of code that the computer will run, one step at a time. You can think of a method as defining a specific task, and how to actually do it.

Computers are very dumb and must be told exactly what to do. Each method describes, in great detail, exactly how to perform some specific task.

Main is one such method, and defines the “main” task. It has some keywords hanging on the front, including static and void. These are called modifiers , and each modifier gives the computer hints or instructions about how to treat it. We’ll learn what these modifiers mean in time. For the moment, we’re going to ignore what those do, and just say that “This is The Way.”

Similarly, after the name, which is Main, there’s some parentheses and that whole string[] args bit.

Each method contains statements –instructions for the computer to run. Console.WriteLine("Hello World!"); is one such statement. As you can probably guess, this particular statement has the console write a single line containing the text "Hello World!".

It is worth pointing out that Console is a class that somebody defined somewhere else (as a part of C#), and WriteLine is a method. This line says, specifically, “Find the thing in the system that is called Console, and have it run its task (method) called WriteLine.” The "Hello World!" in the parentheses hands off some extra information to Console to use as it runs the task identified by the WriteLine method.

How Programs Run

Let’s talk about how your code is executed when you tell it to run.

The pathway the computer takes through your code is sometimes called the flow of execution , or control flow .

Your C# program begins at the very beginning of your Main method. (In fact, if you renamed your Main method to Maine and tried to run it, it would fail!)

The flow of execution generally goes in sequence: one instruction after the next, from top to bottom. We’ll later see some ways to get the flow of execution to do other things like skip some instructions or repeat instructions.

The other way the flow of execution can change is by going “into” and out of things. When the computer reaches a place where it sees it needs to run a method that you name, such as the WriteLine method, the computer takes note of where it is currently at in the method it is already in (Main) and then jumps over to the identified method (WriteLine) and runs the code it finds there, from start to finish. Once finished, it will leave the method and come back to where it left off in the original method.

Officially, going into a method is called calling or invoking the method. Leaving a method and going back to where it came from is called returning from the method.

So when we tell our program to run, the following happens:

  1. The computer finds our Main method.
  2. It starts running there.
  3. It begins running the first statement in the Main method.
  4. It sees that it is being asked to go to the Console class and find its WriteLine method.
  5. It makes a note of where execution is in the Main method, and jumps over to the WriteLine method.
  6. The WriteLine method executes by following any statements it encounters over there.
  7. The WriteLine method completes and the flow of execution returns to Main, at the spot that was noted in Step 5.
  8. Execution picks back up in Main, which encounters the end of the Main method.
  9. When the end of the Main method is reached, the computer knows it is done running your program.

We’ll see many more examples of working programs soon, so if you’re still unsure about how all this code is working, be patient.

using Directives

There is one final piece of information about the code that came from the template that we need to discuss. It is this line:

using System;

As we saw with our own code, classes can live in namespaces. Our Program class is defined in the HelloWorld namespace.

In fact, classes are nearly always defined in a namespace somewhere.

The Console class is defined in a namespace as well: the System namespace.

In C# code, you can usually refer to members of something by using a .. We see that with Console.WriteLine. WriteLine is a member of Console.

Since Console lives in the System namespace, we could have also used System.Console.WriteLine to access the WriteLine method. That’s kind of long, though. It’s like when you’re in trouble and your parents call you by your full name. It’s a lot to type out.

Look again at this line in our program:

using System;

This is called a using directive. It tells the computer, “I’m not going to use ‘full’ names for everything. If you see a name and don’t know where to find it, check in this namespace.”

It is only because of this line that we can even write a plain old Console.WriteLine. We would otherwise need to write System.Console.WriteLine every time we wanted to use it!

As we go, we’ll encounter code that lives in other namespaces, and we’ll add more using directives to our code, but most files will start with using System; because it is so useful.

Top-Level Statements

Before we go any further, do the following:

Delete everything in your code and replace it with just this:

System.Console.WriteLine("Hello World!");

That’s it. A single line.

Now run that code.

The version we started with is the more traditional way to write C# code. It is still very common. (Way more common than not.)

This new, single-line version is much newer (C# 9, which arrived in November of 2020). It is called a top-level statement.

Basically, when you write code the “short” way, it will automatically make a Program class and a Main method for you, and place the code you write inside of that method.

It is much shorter than the traditional approach, and that makes it better, in many ways. But it still seems like it is relatively uncommon, and some people don’t like that it “hides” a lot of details about what is going on.

Either approach can work, and you should try out both and see which you prefer.

Top-level statements deserves one more example before we move on:

using System;

Console.WriteLine("I'm sorry, Dave.");
Console.WriteLine("I'm afraid I can't do that.");

This, too, can be an entire program. You can see how you do using directives when using the top-level statement style, as well as multiple statements.