Educational: My First C# Program


Objective: Download the tools needed to develop your first program, then actually write your first program.

Tool(s) used:

Greetings,

I left off last post lecturing about C# and the .Net Framework. I spent some time going into detail about how the .Net Framework works, what types of software exists out there in the virtual world, and how I perceive C# to fit into the grand scheme of things. I also gave my opinion on C# and .Net and that I would be using them in my lectures. If your interest is in .Net and C#, then you’ve come to the right place.

I’m going to start off with the first hands-on lecture by showing how to download the software needed to write your first program, and actually go into detail to help you write your first program.

Let’s begin!

First, where do you think programmers write code? How do you think the code actually tells the computer to do something? When I first started, I wrote my code in notepad and ran a separate program to compile and execute that code… well, those days are long gone (and thankfully).

Microsoft has been releasing versions of a program called Visual Studio for over a decade now. Visual Studio (as the name suggests) is a visual aid in your pursuit of writing code. It provides a lot of useful tools and tidbits that allow you to do your job easier. Visual Studio is an IDE (Integrated Development Environment), which is a fancy way of saying, “the place in which code is written”. You simply open up Visual Studio, and begin writing your code. Periodically you run or test your code to make sure it works. When you’re all done, you compile your code into an executable and deploy the executable to your machine, your friends, family, or the world. Visual Studio is not the only IDE available. There are a lot of independent and open source IDEs available out there, but Visual Studio is an industry standard, and it’s free (the Express editions are anyways).

Step 1: Obtaining Visual Studio

Now we can begin by downloading Visual Studio 2010 Express (C#) Edition.

Navigate to http://www.microsoft.com/express/Downloads/#2010-Visual-CS

From there, select your language of choice within the “Select language…” ComboBox.

Visual Studio 2010 Express C# English Edition

From there, follow the dialogs on-screen to install Visual Studio 2010 Express C# Edition onto your PC. After the install is complete, you can continue on to the next part of this lecture.
Step 2: Creating Your First Project
Now that you have Visual Studio 2010 Express installed, find it on your PC (most likely your Start menu) and open it.
Proceed through to the Start Page. When you get there, it will look something like this:
Visual Studio Start Page
From here, you will proceed to create a Project. A Project in the context of Visual Studio is essentially a module of your program. It could be your entire program, or it could be one part of your program. A Project is the second highest housing container within Visual Studio. The highest container type is called a Solution. A Solution contains one or many Projects, and a Project contains code files. In the most simple case, you would have one Solution, which houses one Project, which houses your code files.
Click on “New Project” from the Start Page. Here you are presented with the “New Project” dialog. This screen provides you with a bunch of templates to choose from when creating a new Project. Like I said before, a Project houses your code files, and a templates shown here are just there to guide you in the right direction.
Here’s a brief description of some of the templates:
  • Windows Forms Application – Provides a template which when selected, gives you all the starter code for an empty Windows Forms application. Just gives you a basic Window with no controls on it aside from Minimize, Maximize, and Close.
  • WPF Application – Provides a template which when selected, gives you all the starter code for an empty Windows Presentation Foundation application. Just gives you the basic Window with no controls on it aside from Minimize, Maximize, and Close.
  • Console Application – Gives you all the starter code needed for a basic Console application. A Console application is an application that runs from start to finish (top-down) and then exits. It runs within a console (command prompt).
  • Class Library – Gives you an empty project with one class added to it (a class will be explained later). A Class Library project type is used when you want the Project to be used as part of an application, but not be the application itself (ie: a Reference).
  • Empty Project – Gives you a new Project with absolutely no code files in it.

For our first program go ahead and select “Console Application” and give it a name of “MyProgram”.

You’ll notice a few things take place.

  1. The “New Project” dialog closes
  2. A new Solution and Project have been added to the Solution Explorer on the right hand side of Visual Studio with the name of “MyProgram” on each of them
  3. A file has been added to the MyProgram Project called, “Program.cs”
  4. Program.cs has been opened and is ready for editing in the Visual Studio editor

So let’s look at each of these.

Step #1 is pretty expected behavior, but what about Step #2? Why is there a Solution AND a Project? And both with the same name? If you remember on the “New Project” dialog, you gave your Project a name of “MyProgram”. You were in-fact naming the Project and the Solution. You could have chosen to give your Solution a different name, such as “MySolution”, but for our sake it didn’t matter, and if you don’t explicitly tell it to change names, then it will use the same Project name for the Solution name.

Notice the two folders and one file under the MyProgram Project.

Properties and References are added to every Project by default. Properties contains some basic information about your Project (the properties of your Project). If you expand the Properties folder and notice the AssemblyInfo.cs file within it and open it, you’ll see a bunch of mumbo jumbo that essentially is just defining your new program’s version and such. At the bottom of that file you can see the assembly version. This is the same version that will show up if you were to right-click on the program in Windows and select Properties. Now, close out of AssemblyInfo.cs if you opened it (to close out of an opened file in Visual Studio, simply locate the tab with the name of the file and either click the “X” at the right hand side of it, or right click->close it, or simply middle mouse click on it.

The References folder, if you expand it, you’ll see contains numerous references. This may look complicated, but in actuality is a very simple concept. Think back before to the “New Project” dialog. Remember the choice on there for Class Library? I stated before that a Class Library Project type is only to be used when you want it to be part of your application, but not itself be your application. To better understand this, consider this example. Imagine you were creating a program that acted as a Calculator. You would create a nice looking UI that had nice buttons and such that any user could understand just by looking at it. However, it is considered bad programming if you simply put all of your math and calculation logic in the same Project. What if you one day created another program that could benefit from the math calculations you did in your calculator Project? That’s where Class Library Project types come in. A Class Library isn’t your application, but it can be used by your application. So, you could create a Math Class Library, and a Calculate Class Library, then you could re-use those in multiple programs! In order to use a Class Library Project type in another Project, the other Project must add a Reference to the Class Library Project. Remember that a Solution can contain multiple Projects. The Projects don’t just magically know about each other within the same Solution. Projects only know about other Projects that they contain a Reference to. So to go back to the References folder of your new Project here, you can see that it contains some References already. These References are to some very common Class Library Projects that Microsoft has provided for you. If you take a minute, you can actually right-click on the References folder, and select Add Reference. Go to the .NET tab and notice all the Class Libraries that already exist! Microsoft has added hundreds of them in the .Net Framework, and they are always adding more in updates. This is the glory of the .Net Framework. It has a lot of code written for you already, so you can re-use a lot of common tasks without needing to write the code each time! Go ahead and close out of the “Add Reference” dialog, and collapse the References folder.

Now let’s go on to Step #3 (“A file has been added to the MyProgram Project called, “Program.cs””)

Let’s dissect this file. Just by looking at it you can see its name. “Program”, followed by “.cs” .  “Program” is the name of the file added to ALL Console Application Project type templates. It really is your program. If you were to run your program, it would execute the Main method in there (we’ll get to that later). The “.cs” is simply the file extension. Just as files on your Windows PC have file extensions, so do code files. This one (“.cs”) simply means “class”. This is a class file. A class is a container of members. Going back to my example of if you were to create a calculator application, let’s say you wanted to create a way to handle all of the math operations in one location. This is where classes come on. You could create a new class (.cs file) called something like “BasicMath”, which had a bunch of different methods for adding, subtracting, dividing, multiplying and so forth. A class really is just a container for members of the class. In the case of our Program.cs file, the class is conveniently called “Program” (note: It is common convention to make the name of the file the same name as the class within it). And it is the container for our program’s heart. It contains a method called Main (which in our BasicMath example, could be something like Add, or Subtract), which is the heart of our application. When our application is executed, everything inside of Main will execute from top to bottom. When it hits the bottom of the Main method, the program will exit.

Looking at Program.cs some more, you’ll see a “namespace MyProgram” surrounding the class. A namespace is essentially a house to a class (or classes). You can have many classes within a namespace. It is common practice to name a namespace according to the folder hierarchy it appears in on the file system. IE: If your Project had the following structure:

MySolution

-MyProject

–Folder1

— Class1.cs

— Class2.cs

— Folder2

— Class3.cs

— Class4.cs

Then your namespaces for Class1 and Class2 would be something like, “MyProject.Folder1” and your namespaces for Class3 and Class4 would be “MyProject.Folder2”.

Namespaces are very helpful because they provide another layer of organization to your application. With namespaces, you can provide a naming scheme to different parts of your application, such as, “Calculator.Math”. This type of namespace would be expected to house a bunch of math related classes. Or “Calculator.UI”, would expect to contain the UI specific files for your application.

Looking back at Program.cs you’ll see it has some “using” statements at the top of the file. Remember the References information I provided you with earlier? A Project can contain one or many References to other Projects. However, just because your Project contains References to other Projects doesn’t mean that you can simply start using those other Projects’ classes. You must add a “using” statement, pointing to the namespace to use. That’s right, following the “using” keyword is the name of the namespace you want to “import” into the current file. Adding using statements to the top of your file doesn’t hurt your program any, but it’s not common convention to just go and add a bunch of usings up there.

Step 3: Writing Your First Line of Code!

Now let’s write our first line of code!

Since we know we have a Project of type Console Application (that’s the template we chose off the “New Project” dialog), then we know that when we run our application, it will present us with a command prompt window (console window), but just to be sure let’s run our program right now.

To run your program, simply press “F5” on your keyboard (or go to Debug on the menu up top, and select “Start Debugging”). If you have a quick eye you may have noticed a brief moment where a black rectangle was present on the screen and then disappeared. This rectangle was actually our console window… it was our program! If you look at the Main method in your class, you’ll see it has nothing in the body of it (the body of a method is everything in between the opening and closing curly brackets ‘ { ‘ and ‘ } ‘ ). Since our Main method is the heart of our application, and there’s nothing actually inside the Main method, then it is actually acting just as intended. It has nothing to execute so it simply just starts and then stops and closes right away.

To get our program to continue running without closing, we’ll add our first line of code!

In the body of the Main method, add the following line:

Console.ReadLine();

Let’s examine this line of code. It starts off with the word “Console”, followed by a period.

What you’re seeing here is the use of another class! In this case, the class we’re using is called “Console”. How do I know it’s another class? Well, Visual Studio has color coded the word “Console” for us in a light bluish color. This at least lets us know that it is recognized by Visual Studio. Another way I know it’s a class is that if I remove all of the using statements at the top of the file (try it now, just use your mouse to select all of them and press the backspace key on your keyboard), you’ll notice that the “Console” word we just added goes to black and a red squiggly line appears beneath it. This is your first sign of an error. Visual Studio is telling us, “Hey! I see you’re trying to use the word Console as a class, but we simply can’t find it!”… well, of course it can’t find it, we just removed the using statement that taught our class how to find the Console class! (press Ctrl+Z (undo) to get your using statements back). The using statement which actually houses the Console class, is “using System;”.

The period ( ‘ . ‘ ) after the Console class is used to tell our program that we want to access something from the Console class. If you remove the period and then add it back you’ll see a pop-up appear with ReadLine selected for you. First, the pop-up that appeared is called Intellisense. Second, it was defaulted on ReadLine because Visual Studio remembered that was the last thing you had selected (unless you copy+pasted my code snippet before). Intellisense is a very (very) powerful feature of Visual Studio (and all good IDEs out there). Basically, Intellisense is a visual aid to help you find what you’re looking for within a class. Do I remember every member of the Console class myself? Of course not… but I don’t necessarily have to – I have Intellisense to help me. I can simply just press the period button on my keyboard following a class (such as Console), and it displays to me a list of all the members of that class. A lot of them are pretty self explanatory as well and don’t require much research to find out what it means.

Then we have the words “ReadLine”, followed by an open and close parenthesis, followed by a semicolon. As Intellisense showed us, ReadOnly is a method off of the Console class. If you mouse over practically anything in Visual Studio, Intellisense will provide tool tips as to what it does. In our case,  ReadLine will wait for user input into the console window (command prompt). Once it has the input, it will continue over that line to the next line. In our case, there is no next line, which is exactly what we want. We want this ReadLine method to sit there and wait for us to press Enter on our keyboard. ReadLine waits for a new line of text to be entered into the console, and when we press Enter, we are sending a new line of text (even though it has nothing on it). Going back to the line of code, the ‘ ( ‘ and ‘ ) ‘ after the ReadLine method are how we actually execute the method. Notice how Console does not have parenthesis after it, but ReadLine does. Well, that’s because Console is a class, not a method. ReadLine is a method, therefore in order to call it (execute it/run it), we need to follow it up with a pair of open and close parenthesis. Then we follow that up with a semicolon ‘ ; ‘. A semicolon is how we end each line of code in C#. It is how we tell our program, this line of code is done, and I am stating so by ending it with a semicolon. If you remove the semicolon (do so now) you’ll notice that a red squiggly line appears after the ReadLine method call. This is because Visual Studio is telling us “Hey, we can’t find the end of this line of code! You may want to consider adding a semicolon here!” Add your semicolon back in.

Now that we have dissected this one line of code, you can take the same steps and dissect other lines of code that you’ll see in the future. Some are more complex than others, but when you learn the basic principle behind most of them, you can figure out the rest on your own.

Let’s run our program again and see what happens… Press “F5” on your keyboard.

Notice how the console window comes up and stays there now! This is not magic… it’s Console.ReadLine();! What’s happening is just as I described above – the program (a console window) will exit when it gets to the end of the Main method. Well, we aren’t letting it get to the end so fast anymore. We’re telling our program to sit there and wait for a new line to be entered into the command prompt. Ok, we can go ahead and send a new line in now… press Enter on your keyboard to send our program a new line. As soon as you do that, you’ll see that the window closes.

We’re almost done! Let’s say something in our console window before we decide to close it.

Go ahead and add a new line or two above the Console.ReadLine statement (remember, we want the Console.ReadLine call to be at the end of our Main method, and if we add any logic to our program, we want it to occur before the Console.ReadLine call, otherwise we simply won’t see it until ReadLine is executed, in which case the program would just reach an end and close before we even noticed.

Now let’s add a message to the console window. Let’s make it say, “Hello, welcome to my first program!”

Since we already know the Console class has a way to Read a new line from the keyboard, we can probably make a guess that it also contains a way to print or write something out into the console as well. Well, it sure does!

Add this line of code to your Main method.

Console.WriteLine(“Hello, welcome to my first program!”);

Let’s finally dissect this last line of code for this hands on tutorial.

It contains the following parts; “Console.”, which we already know is saying we want to access a method or member off of the Console class. Then we see WriteLine, followed by an open parenthesis, followed by some string of text, followed by a close parenthesis… Hmm, this looks a little different from what we’ve seen so far in method calls. Why is there stuff in between the parenthesis this time? Well, that stuff in there is what we call a parameter. A parameter in the context of programming is quite similar to a parameter in most types of uses in the world. It is simply an input variable into a problem or equation of some sort. In our case, the if you mouse over the WriteLine method, you’ll see that the tooltip that appears contains the words, “string value” wrapped around the parenthesis following the word WriteLine. what this tells us, is this method, WriteLine, expects one parameter to be a string. A string is a series of letters and/or numbers, it’s just a bunch of characters on a keyboard. The word “value” is not important, it could say “string blahfoobar” and all you have to worry about is the fact that it expects a string. blahfoobar in this case would just be the name they are giving this parameter. In our case, they named it value, but it doesn’t matter. We know that we need to pass a string as a parameter to WriteLine. If you mouse over WriteLine again and read the description of what it does, it simply tells you that it takes the specified parameter (value) and writes it to the standard output stream (the console window) and automatically adds a new line character at the end of it. But we could’ve guessed that already since it has the word “Line” in the name of the method… meaning, I’m going to Write a Line of text (typically a line in the world of text consists of a new line character at the end of it, don’t worry about this for now if you’re confused). Now that we know our WriteLine call expects a string as a parameter, we can give it the string we said we would earlier… “Hello, welcome to my first program!” (string parameters must be surrounded in quotation marks, just pretend that a string is actually someone saying something… you are quoting what they are saying by wrapping it in quotations.

And then last we follow it up with a semicolon to say this statement is complete.

Now, go ahead and run your new program and you’ll hopefully see the text we told it to say! Press Enter on your keyboard and the ReadLine() call will get hit and continue on to the end of our Main method, which finally closes the window which ends our application.

That’s it!

<closing>

In this tutorial we walked through downloading Microsoft Visual Studio 2010 Express Edition (C# – English), learned about the Visual Studio IDE, created a new Project, learned about the Solution and Project layout and relations, learned about the Project properties, References, and class file type, learned about what a class is, what namespaces are, what a using statement is, what methods are, how to call them, and how to write some text into a console application (among many other things were learned hopefully).

I hope you enjoyed this and if this is indeed your first time with Visual Studio, C#, or programming in general, I hope it was easy to follow.

As always, you can contact me by email or by leaving comments here.

Good luck!

</closing>

Advertisements

5 thoughts on “Educational: My First C# Program

  1. Pingback: Educational: Introduction to Classes | mariocatch on .Net – WPF – VC#

  2. Pingback: Educational: Introduction to Classes (Part 1) | mariocatch on .Net – WPF – VC#

  3. Pingback: Educational: Introduction to Classes (Part 2) | mariocatch on .Net – WPF – VC#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s