Tutorial: Your First C# Program

Today we’ll be making our first C# program. We’ll start off with console programs for now, and then work up to windows form programs and so on. To start off, you should have some sort of IDE/Editor and compiler to run your C# programs. In my case, I’ll be using Visual Studio 2015 for all tutorials. When installing Visual Studio, make sure you have all of the C# developer packages you may want, including app development packages and so on. Once it’s done installing, let’s get started.

  1. Start Visual Studio.
  2. On the menu bar, choose File, New, Project.
  3. The New Project dialog box opens.
  4. Expand Installed, expand Templates, expand Visual C#, and then choose Console Application.
  5. In the Name box, specify a name for your project, and then choose the OK button. For me, the project will be named FirstProgram.
  6. The new project appears in Solution Explorer.
  7. If Program.cs isn’t open in the Code Editor, open the shortcut menu for Program.cs in Solution Explorer, and then choose View Code.

1

Hello World

After opening your newly generated cs file, you should see some code in the text editor along the lines of something like:

If you’d like or if it makes things easier to understand, you can get rid of the usings for collections.generic, linq, text, and threading.tasks for now—however, I wouldn’t recommend removing it just for stability sake. Trust me.

So now, let’s start writing our program. Within the curly-brackets {} under “static void Main(string[] args)”, let’s type Console.WriteLine(“Hello world!”); and under that line, hit enter and type Console.ReadKey();

Console.ReadKey(); is an important function that we’ll include at the end of all of our console programs. It keeps the console from closing until the user presses a key. Without it, the console would run the program and immediately close thereafter—so don’t forget to put it at the very end every time. Also keep in mind that nearly every single line has to have a semicolon at the end. While it’s tedious, it is nice because it keeps C# from being a line-break sensitive language, allowing you to put as many spaces as you want without ruining your program.

To review, you should have something like this:

On Visual Studio at the top, hit the button in the toolbar that says “ Start” to run the program. You should see a console window pop up saying “Hello world!”, and that’s your new program!

2

Starting your program will also save all of your code and compile it into a .exe file for you (In the ProgramName\bin\debug folder of wherever you have your Visual Studio projects saved. By default it is usually in the Visual Studio folder in your user documents folder).

Let’s explain what’s going on here. To start off, using System; let’s us use the basic System packages for C#, the most important being the fact that it’s where all of our Console methods come from for one. The namespace keyword tells us the name of the program we’re using/referencing and also holds all of the information for our program aside from the packages we’re importing, including all of the classes we write in the program for the main class to call, and is very important when writing programs in any C language, especially C++ and C#. Class Program is the body program, which will hold our static void Main(string[] args) {}, the default method that is executed by the console. Whatever code you write in the Main method will be executed by default when you start the program. Console.WriteLine() is a method that prints a new line of text to the console. (You can also do Console.Write() if you want to print without making a line break at the end). Last but not least, Console.ReadKey() as previously stated, waits for a user input before exiting the program or executing the next series of code. You can use it if you want to test bits of code in chunks, rather than all at once.

To clear things up, a method, or function, is a pre-written almost mini-program kinda thing where someone, or you, has already written something that you can call up at any time to do what you need to do. All methods are called by their name, followed by parentheses containing the data to be used in the method. Sometimes methods also must call the name of the class containing the method before calling the method name, like how you have to call Console.WriteLine rather than just being able to say WriteLine. With that, WriteLine is a method that accepts strings. It’s important to know what data type a method accepts for its arguments, because using the incorrect type of data will give you an error message and will prevent your program from compiling. We’ll talk about data types in the next section, but just know that Visual Studio will tell you what data types and overloads a method will allow.

Area and Perimeter

So, now that you understand the basics of C# structure, let’s move on to our first real program. Before we get into writing our program, you need to understand data types, which is how we store our information into variables. For a full list of C#’s compatible data types, check out this list on the msdn website, but for now let’s just stick with a main few: ints, doubles, strings, chars, and bools (also known as booleans).

To make more sense of things:

  • An int is how we store whole numbers, both negative and non-negative included, meaning they can’t hold decimals and automatically round up. It’s important to note that we’ll be using refer to int32, which means they use base 10 and not base 16 which is good since we aren’t using hexadecimal numbers.
  • A double is the most commonly used data type for numbers that include decimals, as they can hold much more information than a decimal data type.
  • A string is a data type that includes letters (or chars) and can hold all types of text. It’s how we store words and pretty much everything that isn’t a number. That’s pretty much all you need to know. Also note that a string can also be referenced as a char array. Strings must be wrapped in quotes, like “This is a string” or “stringhere”.
  • A char is a type of data that literally just holds one keyboard character at a type. It can be useful when creating something such as a grading system or something of the like. Chars must be wrapped in apostrophes, or single quotes, like ‘x’ or ‘$’.
  • Last but not least, a bool, also known as a boolean, is one of the most important data types of them all. It is used to hold a true or a false, and that gives us a huge range of possibilities in our programs.

Now that you understand data types, let’s move on to actually using our variables to properly store data.

When calculating the area and perimeter of a square or rectangular object, you of course need the length of it and the width.

Start out by entering Console.Write(“Enter length: “); which to the console will of course print “Enter length: as you would expect.

Here’s when things get a little weird looking though. So, to declare a whole number variable, let’s use int like we talked about before. It’s best to remember that all variables must have a name that isn’t a C# keyword, so don’t try to name it something like await or new or return. After that, follow it with an = sign and what you want to assign to the variable. Now, to get user input, we have to convert it from a string to our int (because all things typed into the console are all strings since Main calls the parameters of string[] args). To do so, we’d use the handy little method Convert.ToInt32() and to get the user input we user Console.ReadLine().

Now, you should have something that looks just like this:

       

 

If you have that, you’re good to go. Now, do the same thing for width. So after that you should have:

Console.Write(“Enter width: “);

int width = Convert.ToInt32(Console.ReadLine());

Now we’ll calculate it.

Make a new int variable named area and set it equal to the length multiplied by the width. It should look like this:

int area = length * width;

Then of course, print it of with Console.WriteLine(“The area is ” + area);

Also, to save time, effort, coffee, and extra lines, you can also just calculate as you print things off, like so: Console.WriteLine(“The perimeter is ” + (2 * length + 2 * width));

However, it’s important to note that for safety purposes, you should always wrap your calculations within ()’s inside of the method, or else you might print off something like “The perimeter is 2” which would be bad. Note that putting a + inside of the method will include any other data you put within the method call. Use +’s to print off multiple pieces of data in one line, including of various types. With that you can do things like Console.Write(“This is a string” + ‘z’ + 2 + false + 0x35932); and all of them will be printed off without problems, because C# will automatically convert them to strings without the need to implicitly cast them (or set them to a different type of data or object). Last of all, hit Start and run your program, and you’ve made your first calculator!

Our new program should look like this:

 

4

Let’s stop there for now. However, if you’d like to leave notes to yourself in your code, you can put a // on the line you’re working on and everything past that will not be executed by the program, letting you write notes to yourself maybe on something such as what a certain line does. If you put three forward-slashes you can put XML documentation comments, letting you summarize chunks of code, as well as various other features that don’t quite make sense. You can also do multi-line comments using /* and hitting enter for as many lines you want, then close it with */. Or, wrap a block of code in /* and after it put the */ to comment out the whole block of code and keep it from running. Note that comments do not need to be closed off with a semicolon as well. For example:

 

We’ll end the lesson here for today, and pick back up next time with classes and constructors, as well as writing our own methods.