Learning C#: Getting Started

Learning C#: Getting Started

ยท

15 min read

Why did the programmer go to the eye doctor? . . . Because she couldn't see sharp. ๐Ÿฅ

With the obligatory programmer joke out of the way let's dig in to using C#!

Introduction

C# is a powerful and very widely used programming language. As of writing this blog it's sitting comfortably at number 5 on the TIOBE Index list. It's often seen being used in a more enterprise level setting versus something you'll see a lot of new programmers raving about. There are a handful of reasons for this, but I'm only going to mention a couple of them. Probably one of the biggest reasons is that, being a Microsoft product, it often required (emphasis on the past tense, here) a license simply to use a server that could host the C# code. Another potential issue is that it has a bit more set up and configuration than many other languages. Python doesn't require code to be compiled and can be installed and used in minutes. If you're on a Raspberry Pi it's pre-installed.

None of the reasons I mentioned should deter you from learning C#, however. It's very powerful, strongly typed, and now with the latest moves Microsoft has been making with .NET Core, it's portable and can be used on Windows, Linux and even Macs. Let's get started!

Environment Setup

Installing C# is pretty simple. We need to start by installing Visual Studio 2019 (2022 is available as of this writing, but community support for it isn't quite as available, yet). This will be our Integrated Development Environment (IDE) we'll use to write all of our program code with. Once you're there click the "Download Community 2019" button, like in the image below.

Install Visual Studio 2019

image.png

Stick with all of the default settings in the installation to keep things simple. Once you've finished we need to install the additional dependencies to use .NET Core 3.1 with our IDE and C#. We're using 3.1 because it's in a Long Term Support edition and has a ton of information available from community member's if you get stuck.

Install Additional Dependencies

After VS 2019 finishes installing you should see a dialog window that opens that says "Visual Studio Installer" in the top left. If VS 2019 opens but you don't see that window simply click your windows icon on your computer and search for "Visual Studio Installer."

It should look something like this: image.png

Open the installer and then look for your fresh install of Visual Studio 2019. Click the "Modify" button to the right of the install. image.png

Scroll down until you find two windows, one that says ".NET Desktop Development" and the other should say ".NET Core cross-platform development" like the images below:

image.png image.png image.png

Check both of these boxes and then hit the "Modify" button in the bottom right. It might ask you for administrative permissions. Just hit yes or Okay and continue. I would leave the setting to Install while downloading the way it is. This might help speed up the install.

Installing .NET Core 3.1 Dependencies

Once you have that completed all that is left is to install the .NET Core 3.1 SDK (Software Development Kit). We need this in order for our program to run successfully on our machine. If you looked at any of the checkboxes on the right side of the VS 2019 installer you may have noticed it had ".NET Core 2.1 Runtime" available, or checked. The 3.1 runtime isn't available in this installer and needs to be installed from the Microsoft website. Nothing difficult, just one more step in the chain. image.png

Go to the .NET Core 3.1 download page. You should see two options available: one is for the SDK, the other is for the Runtime environment. We want the SDK since that is what we'll be using to develop with. The runtime would be used in your production environment. In order for your code to be parsed and understood by a computer it needs to have the .NET Runtime available to make that "translation" so-to-speak.

I am using a Windows environment with a 64 bit architecture. Select whichever option suits your machine. Example in the image below: image.png

Same as with VS 2019 simply follow the default installation instructions and you should be fine. Once you have that installed we can finally move on to writing our first program!

Creating Your First C# Program

Okay, remember at the beginning of all of this where I said configuration and setup is a bit clunky with C#? Hopefully you're not too deterred at this point and are still reading. If so, pat yourself on the back because the hard part is over. On to the fun part!

For the sake of brevity I'm going to keep our first code example short. We're just going to make a simple hello world app and maybe a tiny bit of math we can interact with.

Open up Visual Studio 2019 (I keep making the distinction of VS 2019 so it's never confused with it's newer cousin, Visual Studio Code). You should see a startup window pop up that looks like the image below. If you don't it's no big deal, simply go to File > Start Window. image.png

From here scroll around and then click on the "Create a new project" option: image.png

Configure your search settings to look like the image below: C#, All Platforms, Console. We are going to use the "Console Application" option, not the "Console App (.NET Framework) option: image.png

We're using the .NET Core version so that we can make our application environment agnostic. Meaning it can run on basically any machine you'd like: Windows, Linux and Mac. Probably more, but I don't know anymore off the top of my head.

Hit Next and then give it a good Project Name. Place it wherever you'd like on your computer. Quick sidebar, but when I first started developing in C# I was very confused why I didn't have to place it in a var/www folder like I did in PHP. This (for those who don't know) is because you can run C# anywhere on your computer. Similar to how Python can be run pretty much anywhere. But, coming from a PHP world where you had to have it running in a specific location when developing (like LAMP or WAMP) it just threw me for a curveball. Anyway, enough ranting, let's keep going.

I am going to name my project "MyFirstConsoleApp" and I'm going to place it in a folder on my C: drive. Notice that I'm also placing it inside a folder that is also named "MyFirstConsoleApp." There are a few reasons for this but I'm not going to get into that here. If you'd like you can just use my habit of putting your project in a folder with the same name. Leave the checkbox to place the solution and project in the same directory alone as well. It's nothing to worry about right now, or really even until you choose how to design your project structure. image.png

Hit Next and then you should see an "Additional Information" section pop up. Make sure you choose ".NET Core 3.1 (Long-term support)" as your Target Framework. This is the last thing we installed to get this working. image.png

Finally, hit Create!

Congratulations! You have just set up your very first C# application.

Writing Your First Program

Okay, again hopefully you're still following along because we're finally to the fun part. Whew!

Once you have your project created you should see the following code open in VS 2019: image.png

So, what does all of this mean? I'll break it down piece by piece here.

  • using System; bit tells the compiler what namespaces it will need to look in to find the classes you are using in your code. Okay, great that made no sense... The why isn't super important right now. Just know that they are there and they are necessary for your program to run.

  • namespace MyFirstConsoleApp is a way for us to organize our code into different areas depending on the location or "domain" the code is being used in. Same as with the using declaration just know that this is here and don't get too hung up on it at this point. The next section of code is where we finally get to see some action!

Now, I have to point out right now that C# is a 100% Object Oriented Programming (OOP) language. This distinction is very important, especially if like me, you are coming from something that is a procedural language, such as PHP or Python, or even JavaScript. Yes, I know, if you're from those languages I can hear the hissing and booing already. Please note: I still use PHP from time to time, I've written plenty of Python and I use JavaScript everyday. I know that both PHP and Python have support for OOP and JavaScript as of EcmaScript 6 also has some support (yes, I know TypeScript is out there too, and I love that to death. I don't write plain JS anymore much #TypeScriptForLife). Anyway, moving on from that side note. Don't throw tomatoes at me, I am not the type of person to play favorites or to say that other languages aren't real programming languages. They all have their use cases, strengths, and weaknesses.

The important bits of your program are right here:

  • class Program is the name that you have given your class. This name should be specific to what the class represents. Also, class names are typically nouns. Think Car, Person, Dog, Cat, etc. The distinction of the noun may seem odd as well, but it will make sense later. (Fun fact: I didn't even know this noun part until after I started my career. Oh well.)

-static void Main(string[] args) This is called a method and this one gets a bit more complicated so I'll break it down piece by piece as well.

Breaking Down Our Method

static means that we don't have to instantiate a new object when we want to access our class. If you're new to OOP don't worry too much about this either. Over time it will make sense. Again, it took me a long time to fully grasp OOP concepts coming from PHP. Don't beat yourself up.

void is our return type. A method (think function in PHP, Python and JavaScript, it's basically synonymous) always has to have a return type. Notice I said type! This doesn't mean it always has to return a value. A return type of "void" returns no value, which is what you see in the default program, here.

The string[] args is called a "parameter." This is what we pass our method (function) when we are making a call to it. This gets a little confusing with the default "Main()" method since it doesn't look like we're actually passing in any values to it. But, there is some "magic" happening when your program first starts that does actually pass some values here. The "string[]" bit specifies that the parameter with the name "args" is of the type string array. More on types later.

Console.WriteLine("Hello World!"); is FINALLY where you get to write your first program code! Woohoo!

Since this is a console app, WriteLine is rather telling, in that it will write whatever message you passed to the method out in the console. So, without further ado let's run the dang thing!

C#, being a compiled language, must be built before it runs. You can do this a few different ways. I'll show you the manual way first, but I prefer the keyboard shortcut. Look for "Build" in the toolbar at the top. Open it and hit "Build Solution." The other option is to use the keyboard shortcut ```Ctrl + Shift + B" to do it more quickly. You'll learn pretty quickly that you're going to be building your code - a lot. image.png

This will compile your files for you (again, let's not get hung up on what all that means just yet) and tell you if you have any build errors. The compiling process, in a painfully simple nutshell, takes the human readable code you have written and it essentially boils it down into something closer (but not totally) to what the computer can read. What the code is ultimately going to do is get to the 1s and 0s that a processor actually reads. But that all happens with the combination of your compiled code and the Runtime tooling that we learned about before.

The great thing about compiled languages is that it helps to catch any bugs in your code for you before you try to finally run your program. This is different from a runtime, or procedural language in that without some additional setup with your IDE you won't know if you broke something somewhere else. This is one of the main reasons you see C# and Java being used in enterprise applications. If you have a team of people all working on code together you end up with a LOT of code that can break. This makes your code scalable and easier to work with.

Next, let's run the thing already!!! Look for a green arrow at the top of your VS 2019 window, like the image below: image.png

Once you've done that you should see the beautiful, and timeless, "Hello World!" message in a console window. image.png

Round of applause for yourself because you just wrote and ran your first C# program!

Alright, we all know that Hello world is a bit boring after you do it enough times. So let's make it do something a little more involved. In your program make it look like the following code snippet:

using System;

namespace MyFirstConsoleApp
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("Hello, what is your name?");
            var userName = Console.ReadLine();
            Console.WriteLine("Hello " + userName);
            Console.ReadLine(); // If your program keeps closing immediately you can add this line
        }
    }
}

Similar to what we saw with Hello World we will change the first message to ask the user a question. What is your name? After that we set a variable equal to the input from the user. Console.ReadLine(); tells the console to accept some user input. In this case it's a string value of a user's name. After that we use the same WriteLine() method to print a dynamic message back out to the user saying hello. If you're unfamiliar with other coding languages, the "+" sign in there is a way to "concatenate" several values together. This can be very useful like in this situation.

Note: I've added an extra Console.ReadLine(); line to my program. I did this because if for some reason you're not running your program in "Debug" mode your console window might be opening and closing really fast. This prevents the window from closing until the user hits any key on the keyboard.

So, having a user input a message is pretty neat as well. How about a simple calculator that adds two values together? Let's do it! Now change your program to be the following code:

using System;

namespace MyFirstConsoleApp
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("Please enter a number:");
            int firstNumber = Int32.Parse(Console.ReadLine());
            Console.WriteLine("Please enter a second number:");
            int secondNumber = Int32.Parse(Console.ReadLine());
            Console.WriteLine((firstNumber + secondNumber).ToString());
            Console.ReadLine(); // If your program keeps closing immediately you can add this line
        }
    }
}

This little program will add two numbers together. There are a few new things here to break down. The first is that I am specifying that "firstNumber" has a type of "int." This is important because C# is a strongly typed language. This is different from JavaScript or Python in that it won't be able to dynamically change a values type through interpretation. So, later on in that same line I tell the program to convert the user's input to an Int32 value. You probably are already thinking, "what happens if I enter a string??" Go ahead and try it! See what happens :)

Additionally, when we output the value of the two numbers we must convert them back to a string using the .ToString() extension method that is available on the int data type. Note that I wrapped the two integer values in parentheses to group them together, then we change their data type to a string to be output in the console.

The way to avoid someone entering the wrong data type is with type checking. You can use the int.TryParse() method, like the example below. If the user enters an incorrect value, you can tell them a message that they must enter a real number.

using System;

namespace MyFirstConsoleApp
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            int firstNumber = 0;
            int secondNumber = 0;

            Console.WriteLine("Please enter a number:");

            string firstNumberInput = Console.ReadLine();
            if (!int.TryParse(firstNumberInput, out firstNumber))
            {
                Console.WriteLine("Please use a real number. Try again.");
                return;
            }

            Console.WriteLine("Please enter a second number:");

            string secondNumberInput = Console.ReadLine();
            if (!int.TryParse(secondNumberInput, out secondNumber))
            {
                Console.WriteLine("Please use a real number. Try again.");
                return;
            }

            Console.WriteLine((firstNumber + secondNumber).ToString());
            Console.ReadLine();
        }
    }
}

I'll keep it short as this has gotten a bit wordy already, but here is the breakdown of this program.

First, we accept the user's input, just like before, but this time we know the input value is a string. Then we check, using int.TryParse() if the input value is actually a number or not. If it's not then we tell the user to input a real number. Otherwise set the variable, either firstNumber or secondNumber, to the input value converted to an integer.

Then at the end since we're dealing with real numbers and not strings we can do some simple arithmetic on them. The return; piece in both logic blocks tells the program that if I fail and have to tell the user they entered an incorrect value then simply return the parser to end the program. There's no point in reading through the remainder of the code if you've already failed here.

Summary

Okay, so if your head isn't spinning already and you made it to the end of this article I applaud you. You learned a ton about C# and hopefully got everything working just fine. As with any language this is just a tiny fraction of what is out there that can be done in C#. If there was anything I missed or that you would like to know more about please don't hesitate to reach out in the comments or via Twitter. My links are all on my blog. I am learning how to teach and blog as well as how to write and I don't claim to be perfect. I hope to teach someone else and to help kick start their journey into a fantastic world that I find myself lucky to be a part of. I envy the start of your journey.


Visual Studio 2019: docs.microsoft.com/en-us/visualstudio/relea.. .NET Core 3.1: dotnet.microsoft.com/download/dotnet/3.1

Photo by Emile Perron on Unsplash

Did you find this article valuable?

Support Charles J by becoming a sponsor. Any amount is appreciated!

ย