Top-Rated Free Essay
Preview

Introduction to the C# Programming Language

Powerful Essays
5537 Words
Grammar
Grammar
Plagiarism
Plagiarism
Writing
Writing
Score
Score
Introduction to the C# Programming Language
Introduction to the C# Programming Language

[pic]

Visual Studio Express:

Introduction to the C# Programming Language

Author: Rich Tebb

Company: Content Master Ltd

Introduction

The Visual Studio Express family provides a free, lightweight, and easy-to-learn suite of programming tools that are aimed at the hobbyist, novice, and student developer. Many people in this category will not have had any formal training in computer science, and indeed they may not have any programming experience at all. If you fall into this category, don’t worry – this guide is for you!
This beginner’s guide is designed for people with little or no prior knowledge of computer languages, who want to learn to program by using the C# language. If you have some previous programming experience, maybe in another language or from a few years ago, then you may also find this guide useful. If you are a professional developer, or you are already skilled in one or two programming languages, then you will probably not have much to learn from this document.
Whether or not you have programmed before, you should already be familiar with computers before reading this guide. It assumes that you can perform simple tasks like starting a program, and that you are familiar with navigating around your computer by using Windows Explorer.
So what will you learn by reading through this guide? Well, the most important thing you can learn is that Programming is Fun! It’s a great feeling of satisfaction when you finish a program and it does what you want – whether your program is a computer game that you’ve invented, or it controls a robotic device, or serves any other purpose that you can imagine. There may be obstacles along the way – like any challenge, programming can present difficulties – but when you see your finished program working, you can take pride in the fact that you overcame the problems, and converted your imagination into reality.
As well as – we hope – learning that programming is fun, in this guide you will learn how to create a simple program. Your program will include basic but essential programming techniques such as methods, variables, controlling program flow, and how to create your own classes – the fundamental structural units of a C# computer program. Although you will be using Visual Studio tools to create your program, this is not a guide to the full features of Visual Studio. You can learn more about how to use Visual Studio in other MSDN guides.

What is Programming?

Contrary to popular belief, computers are not clever. Left to itself, a computer doesn’t do anything at all – it won’t show the time, or display what you type on the screen, let alone play a video game. The reason that computers are such useful tools, and give the appearance of cleverness, is that they follow instructions, very accurately, very repetitively, and very quickly. For example, when a computer displays a clock, it does so because it has instructions for how to draw every color and tick mark in the clock face, and every line in the clock’s rotating hands, onto the computer screen.
Programming is the act of giving instructions to a computer so that it knows how to perform an action. Fundamentally, these instructions are a series of numbers – to a computer, everything is numbers – in a kind of code where different numbers represent different instructions. The good news is that programmers don’t have to learn all these numbers (the ‘machine code’), because they can write their instructions in a more intuitive form, and then have the computer convert these instructions into machine code.
The intuitive or human-readable form of instructions is called a computer language. Like languages in the real world, there are dozens of computer languages. Some are for specialized tasks and others are more general-purpose. What all programming languages have in common is that they enable programmers to create instructions for a computer without having to learn the computer’s numeric machine code.
In this guide you will learn about C# (pronounced ‘C-sharp’), which is a general-purpose language that you can use to program on the Microsoft .NET platform. You can program in C# by using Visual C# 2005 Express Edition, which is available as a free download from the Microsoft Web site at http://msdn.microsoft.com/express/. The hands-on examples in this guide assume that you have already downloaded and installed Visual C# 2005 Express Edition.

Lesson 1: Your First ‘Hello World’ Program

The first program that students traditionally write when they learn a new language is a program that simply writes a message to the computer screen which reads “Hello, world!” You can create a ‘Hello World’ program by following these instructions:
1. Open Visual C# Express Edition – on the Start menu, point to All Programs, and then click Microsoft Visual C# 2005 Express Edition.
2. On the File menu, click New Project. In the Visual Studio installed templates list, click Console Application, enter MyFirstApplication in the Name box, and then click OK.
3. Visual C# will create an outline program for you, and display the code for that program in the code window.
4. Insert the following line of code (underlined below) into the outline program in the code window:

using System;

using System.Collections.Generic;

using System.Text;

namespace MyFirstApplication

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Hello, world!");

}

}

That’s it! You’ve just written your first program in C#. Let’s run the program to see what happens.

Running the Program

On the Debug menu, click Start Without Debugging (or just press Ctrl-F5). A command prompt window appears that looks like this:

Press a key to dismiss the window.
The program you just wrote might not seem too exciting, but quite a few things happened when you pressed Ctrl-F5.
1. Visual Studio detected that it needed to ‘build’ the program, because this is the first time the program has been run.
2. To build the program, Visual Studio invoked a special kind of program called a compiler, which understands the C# language and knows how to convert it into machine code.
3. The compiler converted the ‘source code’ for your program (which is just a plain text file containing the C# code you wrote) into machine code which the computer can understand.
4. Once the compiler finished, Visual Studio took the compiler’s output – which is your program – and ran that program. Because your program is a console application, Visual Studio actually launched a console window and ran the program inside that window.
5. Once your program had written “Hello, World!” on the screen and finished, Visual Studio displayed the “Press any key” message so that you could see what your program had displayed before the window closed.
You could do all these steps yourself, of course, but it’s much easier to use the Visual Studio Integrated Development Environment (IDE) to do them on your behalf. However, it’s important that you understand what’s going on behind the scenes.

A Closer Look at the Program Code

Now let’s examine the code and see how it works. Although you only added a single line of code to the outline program that Visual Studio generated, the whole program code is important so that the compiler can make sense of that single line.
The code begins with a few lines that introduce the parts of the .NET framework that you will be using in the program. We’ll see how these work shortly.

using System;

using System.Collections.Generic;

using System.Text;

The next few lines specify that you are creating a class called Program inside a namespace called MyFirstApplication.
A class is a container for your code. You must have at least one class in a program, but most programs have several. Classes are a fundamental part of programming in C#, so we’ll look at them in more detail later on.
A namespace is a way of grouping several classes together. The full name of the Program class is actually MyFirstApplication.Program, because it’s inside the MyFirstApplication namespace.

namespace MyFirstApplication

{

class Program

{

Note the funny punctuation mark (‘{’) below the n in namespace and the c in class. These marks are known as curly brackets or braces, and they mark the beginning and the end of a block of code. For every opening brace (‘{’) there must be a closing brace (‘}’) to denote the end of the block of code. (To help you get this right, if you put the cursor to the left of a brace in the code window, Visual Studio highlights both matching braces).
The other thing to note here is that everything between the two matching braces is indented. This is just a convention to help you read the program more easily – the compiler doesn’t care if your code is pretty or not! In fact, you could leave out all the line breaks and write your program on a single line – but you might have trouble understanding what you’ve written.

The next line declares a method called Main. Methods are very important in C# - they are blocks of code that do most of the work in a program. A class can have multiple methods – you can think of methods as actions that your class can perform.
We’ll take a deeper look at methods later, but for now you need to know that the Main method has a special place in a program, because it’s where the program starts running. You can write your methods in any order in the source code, but the Main method will always be where your program starts.

static void Main(string[] args)

{

Finally, we have the code which actually writes the message to the screen. In this case, we use a class called System.Console, which is part of the .NET Framework. Inside the System.Console class there is a method called WriteLine, which writes a message to the console.
As an aside – how is it that the class is called System.Console but we just call it Console? Well, remember the first line of the program:

using System;

That was an instruction to the compiler that your program will be referring to classes within the System namespace by an abbreviated name, by leaving off the namespace at the start. The three namespaces that Visual Studio specified in the outline program – System, System.Collections.Generic, and System.Text – are commonly used namespaces. You are only using the System namespace at the moment in this program, so the other two statements are redundant – unnecessary but harmless.
One small but important point to notice is the semi-colon at the end of the line. You must put a semi-colon after each statement to indicate the end of the statement. As mentioned earlier, the C# language ignores line breaks, so you need to add a semi-colon to show the end of each statement.

Console.WriteLine("Hello, world!");

}

}

}

Lesson 2: Using Methods and Variables

As you saw above, all programs must define a method called Main, which is the starting point for the program. But you can also add other methods. Usually you would create a method when you want to perform the same set of instructions, perhaps with slight differences, several times in a program.

The SayHelloWorld Method

Let’s have a look at how you would create a method. In the source window, right after the closing brace of the Main method, add a newline and then add the following code underlined below:

using System;

using System.Collections.Generic;

using System.Text;

namespace MyFirstApplication

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Hello, world!");

}

static void SayHelloWorld()

{

Console.WriteLine("Hello, World!");

}

}

}

You can see that the SayHelloWorld method has some similarities with the Main method. They both begin with static void, then the name of the method, then some parentheses. The contents of the Main method and the SayHelloWorld method are identical – they both call Console.WriteLine. The main difference is that in the SayHelloWorld method, the parentheses are empty, but we’ll look at that in a minute. Before we do so, let’s see how this method works in action. Modify the Main method so that it calls the SayHelloWorld method instead of calling Console.WriteLine, as follows:
1. In the Main method, delete the line that reads

Console.WriteLine("Hello, World!");

2. Add a line that reads

SayHelloWorld();

Now run the program without debugging (Ctrl-F5). There’s no visible change between the output of the original program and the new version. The only difference is that the Main method no longer writes to the console itself; it calls a different method to write to the console on its behalf.

The SayHelloTo Method

The SayHelloWorld method doesn’t add much to your program – it’s just a way of illustrating how you can create and call a method. Now let’s create a different method, a bit more useful this time because it’s slightly more flexible.
Add the following code underlined below, right after the SayHelloWorld method:

using System;

using System.Collections.Generic;

using System.Text;

namespace MyFirstApplication

{

class Program

{

static void Main(string[] args)

{

SayHelloWorld();

}

static void SayHelloWorld()

{

Console.WriteLine("Hello, World!");

}

static void SayHelloTo(string toWhom)

{

string message = "Hello, " + toWhom;

Console.WriteLine(message);

}

}

}

You can see the obvious similarities between this method and the SayHelloWorld method. But there are some interesting differences, too. Before we examine them, let’s see this method in action. Modify the Main method by adding the following lines right after the line that calls SayHelloWorld:

SayHelloTo("Eric");

SayHelloTo("Sandra");

Run the program without debugging. You should see the following output:

You can probably see the gist of what’s going on here. The SayHelloTo method allows you to specify to whom to say hello, by putting the name of the person as a parameter when you call the method (you can think of a parameter as an input to a method). We put parenthesis “(” and “)” around the parameters after the method name.
Within the SayHelloTo method, we don’t know what the actual value of the parameter will be when someone calls the method. In this program, the values “Eric” and “Sandra” are used; but you could use other values instead. The SayHelloTo method needs a way of handling the value without knowing what the value actually is. To get round this, C# enables us to create a ‘slot’ for the value, and give that slot a name. In this method, we’ve called the slot toWhom. The proper term for the slot is a variable, so called because the slot’s value can vary.

Variables and Data Types

Variables are very important features in C#, or any other programming language. A variable is where you can store information and retrieve it (in computer terms, a variable refers to an area of computer memory where the variable’s value is stored). You must give the variable a name, which you then use when storing or retrieving information from that variable. The name you use for a variable can be anything that you choose, subject to a few restrictions: • Variable names can only contain letters, numbers, and the underscore ‘_’ character. They cannot contain spaces or punctuation. • Variable names cannot start with a number. • Variable names must not clash with other variable names – you cannot use a variable name if it’s already in use in the same part of the program (this restriction isn’t as severe as it may seem, for reasons that will become apparent).
To help the computer set aside the right amount of memory for the variable, C# insists that you specify a data type in addition to the variable name. A data type, as the name implies, denotes what type of data the variable will hold. There are many different data types in C#, and you can create your own; but some examples of the most commonly-used types are:

|Data type |Description |Example |
|int |An integer, 4 bytes in size, which can hold a value between |43 |
| |-2,147,483,648 and 2,147,483,647 | |
|byte |An integer, 1 byte in size, which can hold a value between 0 and|127 |
| |255 | |
|decimal |A number with decimal places, which can hold a value between |10966.2592 |
| |±1.0×10-28 and ±7.9×1028 | |
|string |A sequence (or “string”) of characters |"Hello, World!" |
|char |A single character |'h' |
|bool |A logical value which can be either true or false |true |

Before you can use a variable, C# insists that you declare it. This means that you must specify the type and the name of the variable, so that the program knows what you are talking about before you start to use it. A declaration can be a simple statement such as

int x;

This declares a variable called x which will contain values of integer type. You can optionally assign a value to the new variable when you declare it, as follows:

int y = 43;

This statement declares a variable called y, as above, and then initializes it with a value of 43.
C# imposes an important restriction on your use of variables. It does not allow you to store a value that has one data type in a variable of a different data type. This can be a little confusing at first, because you can’t do some things that seem perfectly obvious. For example, here is some code that declares two variables and assigns values to those variables.

int myInteger = 43;

string myString = "43";

It might seem obvious that myInteger and myString have the same value, but in C# these variables have completely different values. In fact, they have completely different types, so you couldn’t even compare myInteger and myString to see if they were the same value! myInteger can only contain values of type Integer, while myString can only contain values of type String. So even though 43 is an integer value, when we put quotes ("") around it, Visual C# treats whatever is between the quotes as a String value.
Let’s have a look what happens when you try to mix data types. Create a new method in the program by adding the following code after the SayHelloTo method:

static void Wrong()

{

int myInteger;

string myString = "43";

myInteger = myString;

}

This method attempts to assign a string value (myString) to an integer variable (myInteger). C# does not allow this, and you can’t build the program when it contains this kind of error. The following steps show what happens when you try:
1. Press Ctrl-F5 to run the program without debugging.
2. A dialog box appears that informs you that there were build errors. Click No to indicate that you do not want to run the last successful build.
Below the code window, Visual Studio displays the Error List window:

The Error List window contains information about the build errors reported by the compiler. In this case, the error description states: Cannot implicitly convert type 'string' to 'int'
This message[1] indicates that the compiler tried to assign the value of one variable to another variable, but was unable to do so because one is a string variable and the other is an int variable.
Now you have seen what happens when you try to mix data types, you should delete the Wrong method from the program. Run the program again to check that it works correctly.

The SayHelloTo Method Revisited

Now you understand what a variable is, let’s take another look at the SayHelloTo method to get a deeper understanding of how it works.

static void SayHelloTo(string toWhom)

{

string message = "Hello, " + toWhom;

Console.WriteLine(message);

}

The first line is the method header, and tells us the name of the method, along with what parameters it expects a caller to provide. In this case, the SayHelloTo method expects a parameter with a string type, which is identified by the name toWhom. After the header is the opening of the curly brackets that enclose the body of the method.
The first statement in the method body declares another string variable, called message, and assigns a value to message that consists of the string "Hello, " joined to the value of the toWhom variable. The plus sign “+” operator is used to append string values together. So if the caller of the method passes a parameter of "Eric" when it calls SayHelloTo, then the variable message will have a value of "Hello, Eric" after this statement has executed.
The second statement is our old friend Console.WriteLine. There is a subtle difference here from how we’ve used it previously, however. Notice that there are no quotation marks around message. This is because we are passing the value inside the message variable, not the actual string "message", as a parameter to the Console.WriteLine method.
To see the effect of this subtle but important difference, change the second statement so that it reads Console.WriteLine("message" ); - including the quotation marks - and run the program again without debugging. This time, the output from the SayHelloTo method is not what we intended:

Because of the enclosing quotation marks, the compiler has used the literal string "message" instead of the value of the message variable as a parameter to Console.WriteLine. We don’t want SayHelloTo to work like this, so go ahead and remove the quotes around message, then run the program to check it’s working correctly.

Methods That Produce Output Values

So far, the methods you have written simply perform some actions on behalf of your program. By using variables and parameters, a method can perform the same action with different data. But you can also write methods that calculate a value and send that value back to the caller. Add the following code right after the SayHelloTo method:

static string CalculateGreeting(string toWhom)

{

string message = "Hello, " + toWhom;

return message;

}

There are two important differences between this method and the SayHelloTo method. The first is in the method header – instead of saying static void it says static string. This tells the compiler that the CalculateGreeting method produces an output value which has a string data type. The previous methods used void, which indicates that there is no output value from those methods.
The other difference is in the last statement in the method, which reads

return message;

The return keyword indicates that the method should return a value to the caller – in this case, the value to return is the contents of the message variable. The value returned by a method is called the return value or the result.
What the CalculateGreeting method does is to perform a calculation, and then send the result of the calculation back to the code that called the method.
Now modify the first statement of the SayHelloTo method, so that it reads

string message = CalculateGreeting(toWhom);

This statement is a method call, just like when you called SayHelloTo from the Main method. The difference is that the program takes the result of CalculateGreeting and assigns that value to the message variable. Run the program to check that it works, and that you still see the same console output as before.

Lesson 3: Controlling Program Flow

So far, our program has operated in a straightforward sequential manner. The program starts executing in the Main method, and proceeds until the end of that method, with a couple of diversions into other methods along the way. Those methods, in turn, simply start on the first statement of the method, and carry out every statement until they reach the end of the method. When each method ends, the program returns to the piece of code that called that method; and when the Main method ends, the program ends.

Conditional Behavior and Expressions

But what if we want to make the program behave in a slightly different way under certain conditions? This is known as conditional behavior, because the behavior of the program depends on specific conditions being met when the program is running – “if this condition is true, then do this, else do that”. As an example, let’s change the CalculateGreeting method so that it gives a different greeting message depending on the person whom it is greeting. Replace the existing CalculateGreeting method with the following code:

static string CalculateGreeting(string toWhom)

{

string message;

if (toWhom == "Eric")

{

message = "Hi, " + toWhom;

}

else

{

message = "Hello, " + toWhom;

}

return message;

}

In this version of the CalculateGreeting method, we use an if statement to test the value of toWhom. If the value of toWhom is equal to "Eric" then the method returns one greeting, otherwise it returns a different greeting. By now it will be easy for you to guess what the output will be when you run the program:

In the if statement, notice that there is a double equals sign – it’s not a misprint. In C#, the single equals sign is known as the assignment operator, and you use it when you want to assign the value of a variable. The double equals sign is called the equality operator, and you use it when you want to test two values to see if they are equal. There are a few other comparison operators in C#:

|Operator |Description |
|== |Equality. The expression has the value true when the left hand and right hand values are equal, false |
| |otherwise. |
|!= |Inequality. The expression has the value true when the left hand and right hand values are not equal, |
| |false otherwise. |
|< |Less than. The expression has the value true when the left hand value is less than the right hand value, |
| |false otherwise. |
|> |Greater than. The expression has the value true when the left hand value is greater than the right hand |
| |value, false otherwise. |
|= |Greater than or equal. The expression has the value true when the left hand value is greater than or |
| |equal to the right hand value, false otherwise. |

Let’s just pick up on a point there. What exactly does “the expression has the value true” mean? Well, to use the example from the CalculateGreeting method, the underlined part is the expression:

if ( toWhom == "Eric" )

When the program runs, the expression is evaluated (this is a computer-speak term for ‘worked out’) and the result determines which of the following code blocks is executed. If the toWhom variable has the value "Eric", then the expression toWhom == "Eric" evaluates to true. In this case, the program executes the code block following the if. If toWhom has some other value, then the expression evaluates to false, and the program skips the if code block, and executes the code block following the else. In C#, you don’t actually need to provide an else section. If you omit this section, then the program will continue execution after the if code block.
These kinds of expressions that evaluate either to true or to false are called Boolean expressions. They are very common in computer programming, which is why they have a special word to describe them. The bool data type, introduced above, holds Boolean values.

Looping and Iteration

Part of the power of computers is that they can perform tasks repetitively, and for that we need a way of telling our program to repeat itself. The technical term for this repetitive behavior is looping. A loop is a series of instructions that is repeated until a certain condition is met. Usually a loop contains a Boolean expression that determines whether to continue looping or to stop.
Let’s look at an example of a loop. We will change the program so that it repeatedly asks for a person’s name, and then displays a greeting, until someone just presses the Enter key. Modify the Main method so that it looks like this:

static void Main(string[] args)

{

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

string name = Console.ReadLine();

while (name != "")

{

SayHelloTo(name);

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

name = Console.ReadLine();

}

}

Run the program. When prompted, enter a name and press Enter – you can try this as many times as you like. When you get bored, just press Enter without typing a name. Depending on how quickly you get bored, the output will look something like this:

The first point about our new Main method is that it uses two methods that we haven’t used before: Console.Write and Console.ReadLine. Console.Write is almost identical to Console.WriteLine, except that it doesn’t add a line break after it has written the text. Console.ReadLine is a somewhat new concept, because it reads from the console rather than writing to it. When your program calls Console.ReadLine, the program pauses until the user presses the Enter key. The return value from Console.ReadLine is a string containing the text that the user typed before pressing Enter.
The important change in the Main method is the use of the while loop. This is how the while loop works:

1. At the start of the loop, the program evaluates the while condition, which is a Boolean expression like the ones you have already seen.
2. If the condition is true, then the code block is executed, otherwise the program skips over the code block and continues from there.
3. When all the statements in the code block have executed, the program loops back to the top of the while statement and evaluates the conditional expression again.
In our loop, the conditional expression will be false once the user presses Enter without typing anything else. In this case, the return value from Console.ReadLine is an empty string, which is represented in C# by two double-quotes with nothing in between. Once this happens, the program skips over the code block and continues with the next statement.
In summary, a while loop repeats while an expression continues to be true. The loop will exit the first time the expression evaluates to false.

The for Loop

The while loop is useful when you want to repeat a code block for an uncertain number of times. What about when you already know how many times you want to repeat the code block? The tool of choice in this situation is the for loop, which you use to repeat the loop for a certain number of times.
Let’s say that we want our program to greet three people only, no more and no less. Here’s how you should modify the Main method to loop three times:

static void Main(string[] args)

{

for (int i = 0; i < 3; i++)

{

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

string name = Console.ReadLine();

SayHelloTo(name);

}

}

The for loop looks a little more complex than the while loop, because there are three parts to the for clause, separated by a semi-colon. The diagram shows the parts of a for clause, using the example above. Here’s how it works:

1. The initializer statement is executed only once, at the start of the loop. It declares an integer variable called i and assigns it the value 0.
2. The condition is a Boolean expression that is evaluated each time the loop is repeated (including the first time), just like in a while loop.
3. If the condition evaluates to true, then the code block is executed.
4. Finally, the iterator statement is executed after all the statements inside the for code block, each time the loop repeats. (The statement i++ is an instruction to add 1 to the variable i. So each time through the loop, the value of i will be increased by one. It is equivalent to the expression i = i + 1).
In fact, the for loop is just a shorthand for a while loop with a few frills. Here’s the same loop, written using a while statement:

int i = 0;

while (i < 3)

{

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

string name = Console.ReadLine();

SayHelloTo(name);

i++;

}

Looping the right number of times can be confusing – even for experienced programmers! Let’s walk through the example and see how it ensures we only execute the main code block three times. Focus on the condition expression (i < 3), and how the value of i changes each time through the loop. The table below shows the value of the variable i each time the condition is evaluated:

|Value of i |Notes |
|0 |On the first pass through the loop, the initializer statement has just assigned the value 0 to i. The expression |
| |i < 3 is true, therefore the loop goes on to execute the main code block. |
|1 |The next time the condition is evaluated, the main code block has been executed and the iterator statement (i++) |
| |has been executed immediately afterwards. The variable i has the value 1, therefore the condition i < 3 is true, |
| |so the loop continues. |
|2 |On the next occasion that the condition is evaluated, the main code block has by now been executed twice. As on |
| |the previous occasion, the loop continues, because i has the value 2. |
|3 |On the next pass, the main code block has been executed three times in total. This time, because i has the value |
| |3, the condition i < 3 is false, so the loop ends. |

You might wonder why we start counting at zero rather than one. In the above example, we could achieve the same result if we started at one, and replaced the condition with i

You May Also Find These Documents Helpful