Saturday, February 20, 2010

HelloWorld (C#, .NET, Visual Studio 2008)


When programmers dive into a new language, the most common first program to write is the "Hello World" program.

In this episode, we will be writing four such programs to get an idea of the different ways to use C# to create essentially the same, if not exactly the same, result.

Since the "Hello World" program is usually the first step in learning a new language, I will assume we are new to the Visual Studio environment as well. So let's start with creating a new project.

Visual studio comes with many project templates and they are very helpful when you are creating more complex programs but for all our "Hello World" programs, we will start with an empty project. This creates a "Solution" folder which contains a "Project" folder, and, in that, a "References" folder.

A solution can hold many projects so lets rename the solution to "HelloWorld" and rename "Project1" to "HelloWorld1". I said we are going to write four "Hello World" programs so let's make the next three now. If you click on "New Project" in the "File" menu, you'll notice a warning telling us we must "either save or discard changes in the current project before creating a new project." That's because it's actually talking about the "Solution". We cancel that action and, instead, right-click on the solution name and choose "Add->New Project...". It says we must save the current project in order to do so but it's still talking about the solution, not the project. Now we can add the projects, HelloWorld2, 3, and 4 to the solutions folder.

All of these projects will be console applications and by going into the project properties, you can see that is the default "Output type". So we don't need to change anything there and we are ready to write the programs.

Right-click on the project "HelloWorld1" and select "Add->New Item...". Again, we see several code templates to help us design new software but we will choose "Code File" which will give us "A blank C# code file". Let's simply name it "Hello1.cs". We choose the extension "cs" because it is a C-Sharp program.

When we push "Add", it is added to the "HelloWorld1" project folder and automatically opened for editing.

First, we will make a class called "Hello1" and mark it as public so that it can be referenced from anywhere in the program. This is not strictly necessary since this program will only consist of one class but it is important to know how to use in larger programs.

Next, we create a method within the class called "Main". This has been underlined red because every method must have a return type and we indicate that this method will not return a value with the "void" keyword. C# is case sensitive so it is important to name this method with a capital "M". The reason, is that the compiler will look for this method specifically as the first method to run when the application is executed. However, just naming it this way isn't enough. We also need to declare the method as "static" so that it will have the same reference no matter how many instances of the containing class are created. If the "Main" method is not declared "static" then every instance of the class "Hello1" will have its own "Main" method. We'll also declare it as "public" since a larger program may want to reference it from outside the "Hello1" class.

So, we have the "Hello1" class to hold the "Main" method which will be run on execution but right now it's not doing anything. This is supposed to be a "Hello World" program, so let's make it write "Hello, World!" to the console. This is very easy using the .NET Framework Class Library. Just write "System.Console.WriteLine("Hello, World!");". There's a class "Console" in the "System" namespace with a method "WriteLine" that takes a string argument. Notice, we didn't have to create a new instance of the Console object. That's because "WriteLine" is declared "static" just like our "Main" method.

If we try to run this in the debugger, we get an error and that's because it's trying to compile all of the projects which don't have any code files. So, let's just copy "Hello1.cs" to all the other projects for now. Try debugging again and the console window appears just long enough to write "Hello, World!" to a line. It disappears because there's nothing in our program to make it wait. After writing the line, there's nothing left to do so the program simply terminates. We can see it on the screen longer by choosing "Start Without Debugging" from the "Debug" menu. The line "Press any key to continue..." is added by the debugger.

For the second program, we will simply rename "Hello1.cs" to "Hello2.cs".

In "Hello1.cs" we wrote this long line to access the "WriteLine" method. I mentioned that the "Console" class was in the "System" namespace. A single namespace could hold hundreds of class definitions and, if we want to use lots of them, it would be annoying to continue writing such long lines of code. Fortunately, we can simply tell the compiler, from the start, that we're going to be using the "System" namespace. To do that, we just write the line "using System;" at the top of the file and now we can reference the "Console" class directly. That saves a lot of time. We can run this in the debugger but we have to set this as the startup project first or else "Project1" will open in the debugger instead.

For "Hello3.cs" we will see how to access command-line arguments from the program. First we'll indicate that we want to use the "System" namespace as in "Hello2.cs" but now we'll change the "Main" method to accept arguments by telling it to store them in an array of strings called "args". We can access the argument array later to do any number of things. For this program, we will simply tell the user how many arguments they provided and then write them back to the console.

We now have a variable of type array called "args" and we can find the length of it by calling "args.Length". The "Length" property is defined for every array instance. We can write its value to the console in a friendly manner using string formatting. The world of programming likes to start counting at zero so to reference the first value, we write "{0}".

Next, we want to display each value in the "args" array. A very useful code pattern is the "for loop". We create a temporary integer variable "i" starting at "0" and tell it to keep adding "1" as long as "i" is less than the length of the array. Before it adds "1", however, we tell it to write a line to the console containing the value of the array at that index.

I haven't found a way to debug with input arguments so we need to find our program in the console to try it out. Notice that it will take any number of arguments including characters, numbers, and symbols.

Lastly, we have "Hello4.cs". This will just show how to return other types rather than "void". Remember, every method must indicate a return type. Previously, we were returning void and that's all well and good for such a simple program but you may want to return different values depending on the success of the program. Change "void" to "int" to indicate we will return an integer value. If we try to build the program now, we get an error because we're not returning anything. Before we had "void" so it was expected that we wouldn't return anything but now the method is expected to return an integer. We can do that with "return 0". It's common practice to use a value of "0" to indicate everything's normal. Positive numbers generally indicate the method was successful but something changed while negative numbers mean something went wrong.

I'm Justin Mancinelli.
Thanks for watching.



Links:
http://msdn.microsoft.com/en-au/library/9ys06tc9.aspx
http://zpjdevcast.blogspot.com/

No comments:

Post a Comment