Getting Started With C#

Welcome to Getting Started With C#

If you are looking for some guidance on getting started with C# applications, you have come to the right place. This post is all about getting you up and running with C# very quickly by covering a few basics and helping you to write a simple, but illustrative application that will cover a number of important features of the C# programming language.

By the end of this tutorial, you will know how to create a C# console application, understand it’s different parts modify it to get input from the user, and display a very nice greeting. And that is not a bad days work!

If all of this sounds good to you, let’s dive right in and get started!


 

Basic Setup

In order for you to follow along with this tutorial, you are going to need to have a couple things installed on your computer:

  1. .NET Core SDK
  2. Visual Studio Code

If you would like to head over to both of those websites to simply download and install both of those requirements, that will work just fine. If you would like to know a little bit more about them, I have a couple of posts that can help you out with that. You can start with

C# vs .NET Framework

to get a better understanding of what the .NET Framework and .NET Core really are. And you can also have more of a guided setup with my post on

C# Developement: Getting Setup

to help you understand how to set your computer up as well as basic walkthrough of Visual Studio Code.

Once you have both of these installed, you are ready to go!


 

Understanding the .NET Core CLI

When you are getting started with C#, or any programming languages or tools, it’s important to have a basic understanding of what they are and how to use them. In our case, the first thing to understand is how to use the .NET Core Command Line Interface (CLI). This is going to be your window into the world of performing lots of operations when it comes to writing C# applications.

Let’s begin with the basics.

Getting Help

The best place to start when using command line tools, IMHO, is with knowing how to get help. With the .NET Core SDK, you can do that with a very simple command:

dotnet -h

This command will print out all the different options and commands you can use at the command line. These commands will vary from configuration to creating and building projects. Here is what my result looks like:

getting started with C#

You will see at the top, that the response also contains the version of the .NET Core SDK that you have installed.

The response is grouped into two main sections: options (that start with two hyphens) and commands (no hyphens).

In order to use the options, you will follow the dotnet command line with the hyphenated name of the option. A common option to use is the version option. Let’s take a look at that.

.NET Core Version

When using .NET Core, it will become important to be able to understand which version you currently have installed. To figure this out, all you need to do is execute the following command:

dotnet --version

The CLI will respond with it’s current version. In my case, I get a response of:

2.1.403

Depending on when you are following along, you may or may not get a different version. Assume that in order to follow along with this tutorial, you should have at least that version or higher.

Installed Project Templates

In order to create .NET Core projects using the command line, you are typically going to use templates. The .NET Core SDK comes with a list of default installed templates that you can use. You can also install additional templates, but we aren’t going to worry about that at the moment.

Let’s begin with seeing the list of available templates. To do this we are going to use the new command.

dotnet new

This command asks the .NET Core SDK to give you a list of all the currently installed project templates. For me, the results look like this:

getting started with C#

As you can see, by default, it is a fairly extensive list. You can create console applications, test projects, several different variations of web applications, class libraries, and configuration files. This can seem very overwhelming if you have never seen it before. But we are going to start simply. So don’t worry!

The important thing to remember here is that once you pick a template that you want to use, you will need to make a mental note of the Short Name.

Individual Command Help

If you aren’t sure how to use a specific command, you can get help for it all by itself. As an example, if I wanted to learn more about the new command used above, you can type the following:

dotnet new --help

By following a command name the –help option, you will get more information about what the command does, options for that command, as well as some examples.


 

Creating a New Project

Now it’s time to actually create your project and move on to your journey of getting started with C#. Based on the commands that you learned in the previous section, you already know exactly how to do this.

For a simple starter project, we are going to use the console application project template. And the Short Name for this template is “console”.

Based on checking out the help screen for the new command, you know that it takes a “–name” option that will allow you to give your project a name. Let’s put all of these together to create a new project:

dotnet new console --name Greeting

This command will create a new console application in a new directory with the name of “Greeting”.

To take a look at your new project in Visual Studio Code, use the next two commands to move into the “Greeting” directory and open the current directory’s contents in Visual Studio Code:

cd Greeting
code .

Make sure to use the period after the “code” command. This is what tells Visual Studio Code to open the current directory.

The first time you open a one of the these projects in Visual Studio Code there is a high probability that you will see a little window that pops up in the bottom right corner that looks something like this:

getting started with C#

If you do see this, click the “Yes” button. This will finish some setup with your project and create a couple of files in the “.vscode” folder in your “Greeting” directory.


 

Understanding the Project Structure

After you create your project and open it in Visual Studio Code, and install the required assets, your project is ready for you to write some code. But before you get that far, let’s take a look at the current project structure:

getting started with C#

Let’s take a quick look at what each of the files/directories are for in the project explorer on the left side of Visual Studio Code.

.vscode

The first thing that shows up in the explorer is the “.vscode” directory. This directory contains files that are used by Visual Studio Code to interact with your project. This folder really isn’t required for you to be able to write code, but it will help you run and debug your code, which are both very helpful.

Right now, there are two files in this directory:

  1. launch.json
  2. tasks.json

The “launch.json” file is known as the Launch Configuration File. This files tells Visual Studio Code what the commands are that it can use to run your application and allow you to debug it.

The “tasks.json” file is used to define different types of operations you may want to perform at different points. This could include steps that you want to take before, during, or after the building of your application.

We aren’t going to worry too much about either one of these files for this tutorial, but we will take advantage of the “launch.json” filter later.

bin and obj

The “bin” and “obj” directories are common artifacts of the build process for several languages, especially C#. These two folders are used for the build process of you application. Since C# is a compiled language, there is an special step for taking the code that you write and turning it into an actual program that your computer can run.

This process is known as compilation.

The “obj” directory is a intermediate holding area where certain files created during the compilation process are stored. Typically this folder is a holding place. Towards the end of the compilation process, the intermediate files are “linked” or combined into a resulting binary file that you can actually run. This resulting file, as well as any other files that support it, are then moved into the “bin” folder.

We will see an example of this later.

Greeting.csproj

This is what’s known as your project file. A project file is used to store configuration information about your project that is used by your code editor, in this case Visual Studio Code, as well as during the build process. Typically, changes to this file is done by your editor, but there are instances where you will want to edit it manually. But you aren’t going to need that for this tutorial.

Program.cs

This is where the magic is going to happen! The Program.cs file is the main entry point for your code when you are creating a console application. This is where your application is going to start.

By default, this file is going to look something like this:

using System;

namespace Greeting
{
   class Program
   {
      static void Main(string[] args)
      {
         Console.WriteLine("Hello World!");
      }
   }
}
And this is where getting started with C# really starts!

 

Basic Code Structure

Before you can really write C# code, you need to have a basic understanding of how the code files in your C# application are structured. Using the example above, we are going to walk through the main parts that you will see very commonly.

Using Statements

At the top of the code file, you will almost always see at least one, or more, using statements. A using statement is how you are able to get access to code that is written in different parts of you project in the current file.

For example, if you wrote some code in a different file that you wanted to use in the Program.cs file, you could “bring it in” to the current file by adding a using statement to the top of the file in the form of:

using <namespace_that_contains_target_code>;

In the sample case you see:

using System;

This means that we are going to get access to at least some of the code that is found in the System namespace. I say “some”, because there are ways to hide some of the code. But we aren’t going to worry about that now.

The System namespace is one of many special cases that are provided by Microsoft through the .NET Core SDK that contains lots of reusable code to save you from having to write lots of low level code over and over.

Each using statement at the top of the file needs to end with a semicolon.

Namespace Declaration

In the world of C#, there are several ways to “bundle” and “organize” your code. One of the first ways is through the use of Namespaces. Namespaces allow you to create a logical organization structure around your code.

The name of the namespace doesn’t have to correspond with any folder structure at all, even though most of the time it does. You can name the namespaces anything you want and nest them as much as you want.

In our example, the code file declares the namespace with the name of the current folder, like this:

namespace Greeting

 

Class Declaration

Another method of organization with C# is the use of classes. Classes are also a very important part of Object Oriented Programming, which we will cover in depth later. For now, all you need to understand is that every line of code that you write when using C# is going to live within a class.

EVERY SINGLE ONE!

C# is a class based language. That just the way it is.

In the case of our default code, you see that the class that we have by default looks like this:

class Program

Typically, you can give classes any name that you want. There are lengthy discussions, and even books, written on class naming best practices, but in this case the name “Program” is common as the main class entry point for console applications.

So just leave it as is.

Methods

Within your classes, you can create blocks of code that perform any type of functionality that you want. These blocks of code are known as methods. When adding a method to your class, you will define it using a method signature. A method signature contains several parts, but there are 3 main ones you will always see:

  1. Return Type
  2. Method Name
  3. Parameters

These parts of the method signature are in the following format:

<Return Type> <Method Name> ( <Paramaters> )

 

Return Type

C# is a strongly typed language. This means that every piece of data in your code has a specific, pre-defined data type. This data type can either be one that is defined by the .NET Core SDK or one that you can create yourself. Here are examples of some of the built-in data types:

  • Integers
  • Strings
  • Booleans (true or false)
  • Characters

So, when a method has a return type, this means that the method needs to return a value that corresponds with that type. Methods can also have a void return type, which means it doesn’t return anything at all.

Method Name

The method name is simply what you are going to refer to this method has in different parts of your application. Once again, there are lengthy discussions, and probably books written, on the best practices of naming your methods.

The only one that you should worry about right now is that, under most circumstances, your method name should be a verb.

Parameters

The parameters are the names and data types of the values that you are passing into the method. Your method can use these types by name anywhere within it’s body that is surrounded by curly brackets ( { code goes here } ).

You can pass zero or more parameters to a method that are separated by commas.

The only method in our default code looks like this:

static void Main(string[] args)

In this case, we have a Main method (this is a special name for our console application), that takes an “args” parameter that is an array of strings (an array is a collection of values), and doesn’t return anything. Hence “void”.

The static keyword on the front is a special case that we will worry about later.

Method Body

Most of the code you will write belongs inside of methods, know as the method body. You can write as many, or as few, lines of code inside of a method as you wish. Under most circumstances, each line of code that you write is going to end with a semicolon in the same way that each line of the using statements at the top of the file do.

In the default code in your project, you have what’s know as a Hello World application. The purpose of this type of application is simply to display the words “Hello World” on the screen.

The way to accomplish this task in C# is through the following line of code:

Console.WriteLine("Hello World!");

In this line of code, Console is a class that comes from the System namespace brought in from the using statements at the top of the file. WriteLine is a method in the Console class that writes whatever string parameter you give it to the console. In this case, the console will display the string “Hello World!”.

We will see this in action in just a moment.

Curly Brackets

You have no doubt noticed that there are also several curly brackets peppered throughout the code. In C# applications, curly brackets are used to denote scope. Namespaces, classes, methods, as well as other constructs, use curly brackets to identify there scopes, bodies, so that it is easier to identify which code belongs where.

In addition to curly brackets, all source code that is part of a “parent” should be indented underneath. This adds additional clarity to what code belong in which scope.


 

Running Your Code

Let’s see this default code in action before we start making changes.

Start by selecting the Debug button on the left side of Visual Studio Code. It looks like a bug with a circle and a line through it. It is typically the fourth option in a default installation.

getting started with C#

This is your debug view.

At the top of the screen you will see a green play button that says “.NET Core Launch (console)” next to it. If you take a look at your “launch.json” file that was added to the .vscode folder earlier, you will see that’s where this name comes from.

If you click the play button, Visual Studio Code with compile your code, open the “Debug Console” window at the bottom of the screen, and run your application. Eventually you will see that it outputs “Hello World!”.

There’s a bunch of other “stuff” in there as well, this mostly has to do with the compilation and debugging process. Not really anything you need to worry about at the moment.

getting started with C#

Success!

You can now run your code.

Time to start making some changes!


 

Introducing Our Application

In our “Greeting” application, we want to keep things simple, but introduce a couple of key concepts from the C# programming language. The first thing we want our app to do is ask our name. After we enter our name, the application will combine you name with a sample greeting to create an output string. Finally it will output this greeting to the console.

Let’s take this process one step at a time.

Asking for Input

As we can see in the default code, we already know how to output text to the console. Well, it just so happens that there is another method on the Console class that we can use to get input from the user. It’s the ReadLine method. And it looks like this:

Console.ReadLine();

There are no parameters that we pass to it, but it is going to return a string. The string that it returns is what we type into the console.

Let’s update our program to display a request for the users name.

Change the currently line of code to this:

Console.WriteLine("Please enter your name: ");

Now when you run your application, you should see that text output.

It’s asking for your name, it would be rude not to give it. So, let’s add some code to get the users name.

Storing Data in Variables

You know no what the command looks like to get data from the user, but what do we do with that data to hang onto it?

We use a variable.

A variable is nothing more than a named area in memory where we can store information. Since C# is a strongly typed language, that information must be defined as having a type. Before we can store data in a variable, we must declare it.

A variable declaration looks like this:

string userName;

In this case, the variable name is userName and it’s preceded by its type, string.

Now we have a variable, it’s time to give it some data. To give that variable data, or assign the variable, we use an equals sign.

string userName;
userName = Console.ReadLine();

The return value of the Console.ReadLine() method is now stored in the userName variable. Here I am showing it in two separate lines, but in most cases, you would see this combined into one line like so:

string userName = Console.ReadLine();

Add the above line right after the Console.WriteLine method in your program.

Combining Multiple Strings

There will be many times in your development where you will want to take two strings and put them together into one. This process is know as string concatenation. There are many ways to achieve this, but I am going to show you the simplest one for now.

In order to perform basic string concatenation, you can use the plus symbole (+) and simply “add” them together. The result will a brand new string that contains the two previous strings together.

Let’s give it a try.

Start by creating the main part of the output string in a new variable:

string greeting = "I'm glad you are learning C# today, ";

You define a string value as above putting all of it’s contents in between double quotes.

Now, let’s put our userName variable and greeting variable together:

string fullGreeting = greeting + userName;

With this fullGreeting variable, it’s time to display it on the console.

Show the User a Greeting

Finally, you will use your old friend ConsoleWriteLine again to print a string to the screen:

Console.WriteLine(fullGreeting);

The full contents of your Main method, should now look like this:

Console.WriteLine("Please enter your name: ");
string userName = Console.ReadLine();
string greeting ="I'm glad you are learning C# today, ";
string fullGreeting = greeting + userName;
Console.WriteLine(fullGreeting);

 

Running the Application

At this point, your application is ready to go. But there is a problem.

If you try to run your application as you did before, you will see your line asking for the users name in the Debug Console, but you won’t be able to pass input to it.

Go ahead a try.

This is because the output window in the Debug Console is readonly. So, you can only see data coming out of it, you can send data into it.

But, where there’s a will there’s a way.

Instead of using the Debug Console, let’s actually run our app like it was meant.

Open your command prompt or terminal window that you used to create your project.

You should currently be in the “Greeting” directory. Let’s dig a little deeper with this line:

cd bin/debug/netcoreapp2.1

This line will change your current directory all the way into where you actual application lives.

In that directory, you will see a file named Greeting.dll.

That is your application.

All we need to do is run it, like so:

dotnet Greeting.dll

Now you can interact with your program:

getting started with C#

Congratulations!!!

You created your very own C# application using .NET Core.


 

Where to Go From Here

I’m glad you have succeeded so far, but there is a long way to go. There are many places to go and things to learn about the C# programming language and using the .NET Core SDK. But we will get there in time.

The next thing you should do is save your work so you can refer back to it later on in case you want to remember what you did or even make changes.

The best way to do this, is to store your work in GitHub. If you aren’t sure why should should care about GitHub, maybe you should start by reading my award winning What is GitHub, and Why You Should Care post.

Once you are convinced that using GitHub to store your code is a good idea, have a look at my Getting Started With GitHub post to walk you through the process of creating an account, creating your first repository, and then saving you code to it.

Believe me, you won’t be disappointed.

Finally, if you would like to see my full source code, on GitHub, you can check it out in my Greeting repo.

Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *