The C Sharp (C#) Beginner’s Guide

Manish Kumar
C-Sharp-language
Published in
19 min readDec 18, 2020
The C# Beginner’s Guide

Getting Started

This story contains 4 chapters

Get a quick introduction to what C# is (Chapter 1).

Get set up to start making C# programs (Chapter 2).

Write our first program (Chapter 3).

Dig into the fundamental parts of C# programming (Chapters 3 and 4).

Photo by Brandon siu on Unsplash

Chapter 1: The C# Programming Language

What Exactly is C#?

Computers only understand binary: 1’s and 0’s. All of the information they keep track of is ultimately nothing more than a glorified pile of bits. All of the things they do boil down to instructions, written with 1’s and 0’s.

But humans are notoriously bad at doing anything with a random pile of billions of 1’s and 0’s. So rather than doing that, we created programming languages, which are based on human languages (usually English) and structured in a way that allows you to give instructions to the computer. These instructions are called source code and are made up of simple text files.

When the time is right, your source code will be handed off to a special program called a compiler, which can take it and turn it into the binary 1’s and 0’s that the computer understands, typically in the form of a .exe file. In this sense, you can think of the compiler as a translator from your source code to the binary machine instructions that the computer knows.

C# is one of the most mainstream of the entirety of the programming languages accessible. There are in a real sense thousands, perhaps a huge number of these languages, and each one is intended for its own motivations. C# is a basic broadly useful programming language, which means you can utilize it to create basically anything, including work area applications, worker side code for sites, and even computer games.

C# gives an excellent balance between convenience and force. Different languages give less force and are simpler to utilize (like Java) and others that give more force, surrendering a portion of its simplicity (like C++). Because of the balance it strikes, it is the perfect language for almost all that you will need to do, so it’s an incredible language to realize, regardless of whether it’s your first or your 10th.

What is the .NET Framework?

C# relies heavily on something called the .NET Framework. The .NET Framework is a large and powerful platform.

The .NET Framework primarily consists of two parts. The first part is the Common Language Runtime, often abbreviated as the CLR. The CLR is a virtual machine — a special type of software program that functions as though it is an actual computer. C# code is actually executed by the CLR, instead of being run by the actual physical computer. There are, of course, benefits and drawbacks to this kind of a setup, but it turns out to be a good idea for everything except low-level stuff, like an operating system or a device driver. C# is a bad choice for things like that. (Try C or C++ instead.)

I should also point out that while running your code through a virtual machine may make it a bit slower, in most cases, this isn’t enough to matter. In some situations, it could actually end up being faster. In other cases, you can call outside code that not running on a virtual machine. The bottom line is, don’t stress too much about if the CLR will be fast enough.

Because C# code runs on the .NET Framework, the process your code goes through before executing is a little more complex than what I described earlier. Rather than just a single step to compile your source code to binary executable code, it goes through two steps. Here’s what happens:

The C# compiler turns your source code into Common Intermediate Language (CIL or IL for short).

This IL code is packaged into an .exe file or .dll file, which can be shared with others.

When it is time to run your program, the IL code in your .exe or .dll will be handed off to the CLR to run it.

As your program is running, the CLR will look at the IL code and compile it into binary executable code that the computer it is running on understands. For each block of code you have, this will only happen once each time you run your program — the first time it needs it. This is called Just-in-Time compiling, or JIT compiling.

The other half of the .NET Framework is the Base Class Library, or BCL. The BCL is a massive library of code that you can reuse within your own programs, to accelerate the development of whatever you are working on. This library is much bigger than what you typically find packaged with a programming language (though Java also has a library of comparable size). It is impossible to cover all of this code in this or any book, though we’ll cover the most important stuff. Before trying to build your own code for what seems like a common task, search the Internet to see if it already exists as a part of the BCL.

Chapter 2: Installing Visual Studio

To make your own programs, people usually use a program called an Integrated Development Environment (IDE). An IDE combines all of the tools you will commonly need to make software, including a special text editor designed for editing source code files, a compiler, and other various tools to help you manage the files in your project.

The Installation Process

You can find Visual Studio Community edition here: https://www.visualstudio.com/products/visual-studio-community-vs

Once downloaded, start the installer and follow the steps you see. The installation process takes a while (even hours) depending on your Internet connection. Feel free to get it started and continue reading.

Once installed, it may place an icon on your desktop that you can use, but it will also put it in your Start Menu under All Programs. Look for it under Visual Studio 2019.

Visual Studio will ask you to sign in with a Microsoft account at some point. If you don’t already have one, it’s worth the effort. If you’ve got an MSDN subscription, signing in gives you access to MSDN. It also allows you to sync settings across different computers.

Try It Out! Install Visual Studio. Take the time now to choose a version of Visual Studio and install it, so that you’re ready to begin making awesome programs in the next chapter.

Alternatives to Visual Studio

Almost everyone who writes programs in C# uses some version of Visual Studio. It is generally considered the best and most comprehensive option. However, there are other options available if you’re looking for something different. When choosing an editor, Instructions on how to do various things may not apply in other IDEs.

Visual Studio Code ( https://code.visualstudio.com/ ): A free, extremely trimmed down version of Visual Studio itself, which also runs on Mac and Linux. While the full Visual Studio is useful for full development, it can be pretty heavy. If you’re just interested in making some quick tweaks to some code, Visual Studio Code may be a great additional companion tool to the full version.

MonoDevelop ( http://monodevelop.com/ ): The most popular C# IDE aside from Visual Studio, and it’s free (and open source). It is also cross-platform (runs on a Mac and Linux natively). This has most of the features that you get in Visual Studio, though plugins and extensions are rarer than what you find in the Visual Studio ecosystem.

Xamarin Studio (http://xamarin.com/studio): A customized paid-for version of MonoDevelop with some added features for cross-platform mobile development, such as iOS and Android. This one isn’t free.

SharpDevelop (http://www.icsharpcode.net/OpenSource/SD/Default.aspx): A free, lighter weight IDE than Visual Studio, while still having the key features.

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.

Chapter 4: Comments

Quick Start

  • Comments are a way for you to add text for other people (and yourself) to read. Computers ignore comments entirely.
  • Comments are made by putting two slashes ( // ) in front of the text.
  • Multi-line comments can also be made by surrounding it with asterisks and slashes, like this: /* this is a comment */

What is Comment?

At its core, a comment is a text that is put somewhere for a human to read. Comments are ignored entirely by the compiler.

Why Should I Use Comments?

I mentioned in the last chapter that whitespace should be used to help make your code more readable.

Writing code is actually far easier than reading it or trying to understand what it does. And believe it or not, you’ll actually spend far more time reading code than writing it. You will want to do whatever you can to make your code easier to read. Comments will go a very long way towards making your code more readable and understandable.

Writing comments — wait, let me clarify — writing good comments is a key part of writing good code. Comments can be used to explain tricky sections of code, or explain what things are supposed to do. They are a primary way for a programmer to communicate with another programmer who is looking at their code. The other programmer may even be on the other side of the world and working for a different company five years later!

Comments can explain what you are doing, as well as why you are doing it. This helps other programmers, including yourself, know what was going on in your mind at the time.

Writing comments makes it so that you can quickly understand and remember what the code does, how it does it, why it does it, and you can even document why you did it one way and not another.

How to Make Comments in C#

There are three basic ways to make comments in C#. For now, we’ll only really consider two of them, because the third applies only to things that we haven’t looked at yet.

The first way to create a comment is to start a line with two slashes: //. Anything on the line following the two slashes will be ignored by the computer.

In Visual Studio the comments change color — green, by default — to indicate that the rest of the line is a comment.

Below is an example of a comment:

// This is a comment, where I can describe what happens next... Console.WriteLine("Hello World!");

Using this same thing, you can also start a comment at the end of a line of code, which will make it so the text after the slashes is ignored:

Console.WriteLine("Hello World!"); // This is also a comment.

A second method for creating comments is to use the slash and asterisk combined, surrounding the comment, like this:

Console.WriteLine("Hi!"); /* This is a comment that ends here... */

This can be used to make multi-line comments like this:

/* 
This is a multi-line comment.
It spans multiple lines.
Isn't it neat?
*/

Of course, you can do multi-line comments with the two slashes as well, it just has to be done like this:

// This is a multi-line comment. 
// It spans multiple lines.
// Isn't it neat?

In fact, most C# programmers will probably encourage you to use the single-line comment version instead of the /* */ version, though it is up to you.

The third method for creating comments is called XML Documentation Comments.

How to Make Good Comments

Commenting on your code is easy; making good comments is a little trickier. I want to take some time and describe some basic principles to help you make comments that will be more effective.

My first rule for making good comments is to write the comments for a particular chunk of code as soon as you’ve got the piece more or less complete. A few days or a weekend away from the code and you may no longer really remember what you were doing with it. (Trust me, it happens!)

Second, write comments that add value to the code. Here’s an example of a bad comment:

// Uses Console.WriteLine to print "Hello World!" Console.WriteLine("Hello World!");

The code itself already says all of that. You might as well not even add it. Here’s a better version:

// Printing "Hello World!" is a very common first program to make. Console.WriteLine("Hello World!");

This helps to explain why we did this instead of something else.

Third, you don’t need a comment for every single line of code, but it is helpful to have one for every section of related code. It’s possible to have too many comments, but the dangers of over commenting code matter a whole lot less than the dangers of under-commented (or completely uncommented code).

--

--

Manish Kumar
C-Sharp-language

I write blogs on cyber security, Machine Leaning & C# programming.