The C Sharp (C#) Beginner’s Guide
By: Manish Kumar
Tags: Programming, Beginners Guide, Dotnet, Technology, Csharp

Chapter 3: Hello World: Your First C# Program

In this chapter, we’ll make our very first C# program. Our first program needs to be one that simply prints out some variation of “Hello World!”.

It’s tradition to make your first program print out a simple message like this, whenever you learn a new language.

So that’s where we’ll start. We’ll create a new project and add in a single line to display “Hello World!” Once we’ve got that, we’ll compile and run it, and you’ll have your very first program!

Creating a New Project

Let’s get started with our first C# program! Open up Visual Studio, which we installed in Chapter 2.

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.

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

Creating a New Project

On the left side, you will see a few categories of templates to choose from. Depending on what version of Visual Studio you have installed and what plugins and extensions you have, you may see different categories here, but the one you’ll want to select is the Visual C# category, which will list all C#-related templates that are installed.

Once that is selected, in the list in the top-center, find and select the Console Application template. The Console Application template is the simplest and it is exactly where we want to start. For all of the stuff, we will be doing in this book, this is the template to use.

As you finish up this book, if you want to start doing things like making programs with a graphical user interface (GUI), game development, smartphone app development, or web-based development, you will be able to put these other templates to good use.

At the bottom of the dialog, type in a name for your project. I’ve called mine “HelloWorld.” Your project will be saved in a directory with this name. 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. By default, Visual Studio tries to call your programs “ConsoleApplication1” or “ConsoleApplication2.” If you haven’t chosen a good name, you won’t know what each of these does.

By default, projects are saved under your Documents or My Documents directory (Documents/Visual Studio 2019/Projects/).

Finally, click the Create button to create your project! After you do this, you may need to wait for a little bit for Visual Studio to get everything set up for you.

A Brief Tour of Visual Studio

By this point, you should be looking at a screen that looks something like this:

A Brief Tour of Visual Studio

Depending on which version of Visual Studio you installed, you may see some slight differences, but it should look pretty similar to this.

In the center should be some text that starts 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. We’ll spend most of our time in this window.

On the right side is the Solution Explorer. This shows you a big outline of all of the files contained in your project, including the main one that we’ll be working with, 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 Solution Explorer, it will open in the main editor window. The Solution Explorer is quite important, and we’ll use it frequently.

As you work on your project, other windows may pop up as they are needed. Each of these can be closed by clicking on the ‘X’ in the upper right corner of the window.

If by chance, you are missing a window that you feel you want, you can always open it by finding it on either the View menu or View > Other Windows. For right now, if you have the main editor window open with your Program.cs file in it, and the Solution Explorer, you should be good to go.

Building Blocks: Projects, Solutions, and Assemblies

As we get started, it is worth defining a few important terms that you’ll be seeing spread throughout this book. In the world of C#, you’ll commonly see the words solution, project, and assembly, and it is worth taking the time up front to explain what they are so that you aren’t lost.

These three words describe the code that you’re building in different ways. We’ll start with a project. A project is simply a collection of source code and resource files that will all eventually get built into the same executable program. A project also has additional information telling the compiler how to build it.

When compiled, a project becomes an assembly. In nearly all cases, a single project will become a single assembly. An assembly shows up in the form of an EXE file or a DLL file. These two different extensions represent two different types of assemblies and are built from two different types of projects (chosen in the project’s settings).

A processing assembly appears as an EXE file. It is a complete program and has a starting point defined, which the computer knows to run when you start up the .exe file. A library assembly appears as a DLL file. A DLL file does not have a specific starting point defined. Instead, it contains code that other programs can access on the fly.

Finally, a solution will combine multiple projects together to accomplish a complete task or form a complete program. Solutions will also contain information about how different projects should be connected to each other. While solutions can contain many projects, most simple programs (including nearly everything we do in this book) will only need one. Even many large programs can get away with only a single project.

Looking back at what we learned in the last section about the Solution Explorer, you’ll see that the Solution Explorer is showing our entire solution as the very top item, which it is labeling “Solution ‘HelloWorld’ (1 project).” Immediately underneath that, we see the one project that our solution contains: “HelloWorld.” Inside of the project is all of the settings and files that our project has, including the Program.cs file that contains source code that we’ll soon start editing.

It’s important to keep the solution and project separated in your head. They both have the same name and it can be a little confusing. Just remember the top node is the solution, and the one inside it is the project.

Modifying Your Project

You should see the main text editor, containing text that should look identical to this:

Visual Studio Editor

In a minute we’ll discuss what all of that does, but for now, let’s go ahead and make our first change — adding 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:

C# hello world program

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

Try It Out! Hello World! It’s impossible to understate how important it is to actually do the stuff outlined in this chapter. Simply reading text just doesn’t cut it. So follow through this chapter, one step at a time, and make sure you’re understanding the concepts that come up, at least at a basic level.

Compiling and Running Your Project

Your computer doesn’t magically understand what you’ve written. Instead, it understands special instructions that are composed of 1’s and 0’s called binary. Fortunately for us, Visual Studio includes 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 and run it. Visual Studio will make this really easy for us. To start this process, press F5 or choose Debug > Start Debugging from the menu. Besides you can start the process without debugging by pressing Ctrl + F5 for faster processing of the results.

Compiling Hello World Program

There! Did you see it? Your program flashed on the screen for a split second! (Hang on… we’ll fix that in a second. Stick with me for a moment.)

We just ran our program in debug mode, which means that if something bad happens while your program is running, it won’t simply crash. Instead, Visual Studio will notice the problem, stop in the middle of what’s going on, and show you the problem that you are having, allowing you to debug it.

Hurray!!! 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 see it!

Approach: Put another line of code 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; namespace HelloWorld

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Hello World!");

Console.ReadKey();

}

}

}

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

Try It Out! See Your Program Twice.

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 made. I’ll try to explain what each one does so that you’ll have a basic understanding of everything in your simple Hello World program.

Using Directives

using System;

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 made that we want to be able to access.

So when you see a statement like using System; you know that there is a whole pile of code out there named System that our code wants to use. Without this line, the C# compiler won’t know where to find things and it won’t be able to run your program.

Namespaces, Classes, and Methods

Below the using directives, you’ll see a collection of curly braces (‘{‘ and ‘}’) and you’ll see the keywords namespace, class, and in the middle, the word Main. Namespaces, classes, and methods (which Main is an example of) are ways of grouping related code together at various levels. Namespaces are the largest grouping, classes are smaller, and methods are the smallest.

Methods are a way of consolidating a single task together in a reusable block of code. In other programming languages, methods are sometimes called functions, procedures, or subroutines.

Right in the middle of the generated code, you’ll see the following:

static void Main(string[] args)

{

}

This is a method, which happens to have the name Main. I won’t get into the details about what everything else on that line does yet, but I want to point out that this particular setup for a method makes it so that C# knows it can be used as the starting point for your program. Since this is where our program starts, the computer will run any code we put in here.

When one thing is contained in another, it is said to be a member of it. So the Program class is a member of the namespace, and the Main method is a member of the Program class.

Classes are a way of grouping together a set of data and methods that work on that data into a single reusable package. Classes are the fundamental building block of object-oriented programming.

In the generated code, you can see the beginning of the class, marked with:

class Program

{

And later on, after the Main method which is contained within the class, you’ll see a matching closing curly brace:

}

Program is simply a name for the class. It could have been just about anything else. The fact that the Main method is contained in the Program class indicates that it belongs to the Program class.

Namespaces are the highest level grouping of code. Many smaller programs may only have a single namespace, while larger ones often divide the code into several namespaces based on the feature or component that the code is used in.

Looking at the generated code, you’ll see that our Program class is contained in a namespace called “HelloWorld”:

namespace HelloWorld

{

...

}

Once again, the fact that the Program class appears within the HelloWorld namespace means that it belongs to that namespace, or is a member of it.

Whitespace Doesn’t Matter

In C#, whitespace such as spaces, newlines, and tabs don’t matter to the C# compiler. This means that technically, you could write every single program on only one line! But don’t do that. That would be a pretty bad idea.

Instead, you should use whitespace to help make your code more readable, both for other people who may look at your code, or even yourself, a few weeks later, when you’ve forgotten what exactly your code was supposed to do.

But as an example, compare the following pieces of code that do the same thing:

Approach #1:

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

Approach #2:

static void Main(string[] args)

{

Console.WriteLine("Hello World!");

}

Semicolons

You may have noticed that the lines of code we added all ended with semicolons (‘;’).

This is often how C# knows it has reached the end of a statement. A statement is a single step or instruction that does something. We’ll be using semicolons all over the place as we write C# code.