Sei sulla pagina 1di 29

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.

Hello,
3 Sandra
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 43


hold a value between -2,147,483,648
and 2,147,483,647
byte An integer, 1 byte in size, which can 127
hold a value between 0 and 255
decimal A number with decimal places, which 10966.2592
can hold a value between ±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 true
or false

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 message1 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.

1
The compiler error message ‘Cannot implicitly convert type’ is an unusual turn of
phrase. The choice of words hints at two implications:
• Perhaps it is possible to perform an explicit conversion from string to int? This is
indeed the case – we could explicitly call the Int.Parse method to convert from a
string to an int.
• Although the compiler cannot implicitly convert between string and int, perhaps
there are some cases where it can perform an implicit conversion? This is also true – for
example, the compiler will implicitly convert a byte value to an int value, because they
are similar data types.
Don’t worry too much about data type conversion – it is an advanced topic. The
important thing to remember is that, as a general rule, you must not mix together
variables with different data types.
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.
<= Less than or equal. The expression has the value true when the left
hand value is less than or equal to 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
<= 3. The main reason in the above example is convention – in C# it is traditional to
start counting at zero. There are other reasons too, which you will discover as you learn
more about C#.

Lesson 4: Creating Your Own Classes


Way back when we looked at the original Hello World program, you may remember that
the outline code created by Visual Studio looked like this:

class Program

...

[the program code goes here]

...

At that point, we skimmed the concept of classes by saying that they are a container for
code. This is true as far as it goes, but there is far more to classes than merely
containing code.
Classes are fundamental to programming in C#, because they enable you to organize
your code in a sensible way. Just as, in a museum, the curators group related items
together and display them in the same room; in the same way, you can use classes to
group together related parts of your code. The reason in both cases is the same – so
you can find your way around. In a small program like our Hello World program – just
like in a small museum – you can find what you want just by looking through
everything, even if there is no organization. But as you write bigger and more complex
programs, you will find that the way you organize your code helps you to find what you
want. So it is important to understand how you can add structure to your programs by
using classes.

The Greeting Class


Although classes can help you to structure your program, there is no right or wrong way
to do so. To use the museum analogy, a curator might choose to organize the collection
in chronological order, or by the type of artwork – paintings in one area, sculptures in
another – or even alphabetically. Some ways of organization are perhaps more useful
than others, and many books have been written on how best to organize a program, but
ultimately the decision is with the design team.
This guide does not attempt to discuss program design; but you can learn how to create
and use classes in C#. In this section, you will create a class that manages greetings,
which will replace the SayHelloTo method that you wrote earlier. To create the
Greeting class, use the following steps:
In Visual Studio, in the Solution Explorer window, right-click the MyFirstApplication
project, point at Add, and then click Class.

5. In the Name box, type Greeting.cs, and click Add.


Visual Studio creates a new file called Greeting.cs, with the outline code for the Greeting
class, which looks like this:

using System;

using System.Collections.Generic;

using System.Text;

namespace MyFirstApplication

class Greeting
{

Except for the absence of a Main method, this is remarkably similar to our original
Program class. We have defined a class called Greeting, although it has no contents at
the moment. To rectify that, modify the Greeting class so that it looks like this (be
careful to replace only the Greeting class and not the whole file):

class Greeting

private string _recipient;

public Greeting()

_recipient = "Stranger";

public void Display()

string message = "Hello, " + _recipient;

Console.WriteLine(message);

public string Recipient

get { return _recipient; }

set { _recipient = value; }

}
}

Before we examine the Greeting class in detail, let’s see it in action. Go back to the
Program class (click on the Program.cs tab at the top of the code window), and modify
the Main method as follows:

static void Main(string[] args)

Greeting theGreeting;

theGreeting = new Greeting();

theGreeting.Recipient = "Eric";

theGreeting.Display();

Now run the program without debugging. The output looks like this:

In terms of what the program does, there’s not much change here from what we’ve seen
before. In terms of how the program does it, however, this is a whole new ball game.

Using the Greeting Class


Before we examine the Greeting class itself, let’s take a look through our new Main
method in the Program class. The way that we use the Greeting class introduces some
important new concepts.

Greeting theGreeting;

The first statement declares a variable called theGreeting, much like we saw earlier.
The difference between this declaration and the ones we saw earlier is that the type of
the variable is Greeting, rather than int or string. As you learned earlier, this means
that the variable ‘slot’ can only hold a Greeting value. The slot is initially empty, so the
next line puts something in the slot:

theGreeting = new Greeting();


This statement creates a new Greeting object and stores it in the theGreeting variable.
What this means, and why you must do this, requires a bit of background explanation.
When you defined the Greeting class in Greeting.cs, you did not actually create a
Greeting at all. The class definition simply describes a conceptual Greeting. It is a
blueprint, rather than the airplane itself. If you like, it tells the compiler “I am defining a
class of objects in my program, called Greeting; and this is what a Greeting object
would look like and how it would behave.”
To use one of these conceptual Greeting objects, you must create a new object based
on the Greeting blueprint. This new object is an instance of the Greeting class, and
the process of creating the object is called instantiation. In C#, you use the new
keyword to instantiate a class.

theGreeting.Recipient = "Eric";

Now we have created a Greeting object, we can start to use it. As you will see below,
we have defined a property of the Greeting class called Recipient. The Recipient
property represents the recipient of the greeting. In this case, we want to greet Eric, so
we set the Recipient property accordingly.

theGreeting.Display();

This statement calls the Display method on the theGreeting object to display the
greeting on the console. The Display method is also defined in the Greeting class.
You may be wondering why you use the theGreeting variable when you access the
Display method. After all, when you accessed the Console.WriteLine method, you
didn’t need to create an instance of the Console class. The answer is that, when you
define a class, you can define a method by using the static keyword – as we do
ourselves in the Main method. This keyword means that you don’t need to instantiate
the class in order to use the method. You should only use the static keyword in specific
circumstances, which are beyond the scope of this introductory guide.

A Closer Look at Greeting


Now we know how a Greeting is used, let’s take a step by step look through the
Greeting class.

class Greeting

private string _recipient;

The above line declares a variable called _recipient. Note that the variable declaration
exists outside of any method. This means that the variable belongs to the class as a
whole, rather than to any one method. A variable declared at class level is called a
member variable.
The keyword private refers to the visibility of the member variable. By declaring the
variable as private, this prevents any external code from viewing or changing the
variable – effectively, the variable is hidden from any code that isn’t part of the
Greeting class. It is good practice to declare all member variables as private – in fact,
you should hide any of the ‘inner workings’ of your classes by making them private. This
helps each class to be a ‘black box.’ You will see the advantage of this later on.
In case you were wondering, the underscore character ‘_’ at the start of the variable
name has no special significance in C#. It is merely a naming convention, used to
indicate that _recipient is a member variable.

public Greeting()

_recipient = "Stranger";

The Greeting method is a special case. A method that has the same name as the
containing class is called a constructor, and it is used to create an instance, as the
name implies, when the new keyword has been used.
Just now you saw how we declared the _recipient member variable as private to hide
it from any code outside of the Greeting class. In contrast with the variable, we have
declared the constructor as public, which means that code outside of the Greeting
class can call it. Constructors are usually public, otherwise it would not be possible for
outside code to create an instance of the class!
Note that a constructor, unlike any other method, does not specify a return value or
void. The return value is implicit – in this case, the new Greeting instance.
In the Greeting constructor, the only action is to initialize the _recipient member
variable to a default value. In this case, the default value is "Stranger".

public void Display()

string message = "Hello, " + _recipient;

Console.WriteLine(message);

The Display method is an ordinary method like those we have seen before, except that
it is not static. It creates a message based on the recipient’s name and writes the
message to the console.

public string Recipient

get { return _recipient; }

set { _recipient = value; }

The last section defines the Recipient property. A property is a member of a class that
provides access to data in that class in a controlled manner. In this case, the Recipient
property provides access to the _recipient member variable without the need to make
_recipient public.
What’s the deal here? Why not just make the member variable _recipient public, and
do away with the Recipient property? To understand the answer, you first need to
understand how properties work.
A property has a type, just like a variable – in the case of the Recipient property, its
type is string. A property also has get and set accessors, which are like methods but
without the parameters and are represented in C# by the keywords get and set. These
accessors provide access to the property itself. Remember this statement in
Program.Main:
theGreeting.Recipient = "Eric";

This statement sets the Recipient property to have the value "Eric". Behind the scenes,
this calls the set accessor in the Greeting class. The set accessor looks like this:

set { _recipient = value; }

Inside the set accessor, there is a pre-defined variable named value that holds the
value being assigned to the property. In this case, that value is stored in the
_recipient member variable.
The get accessor works in the opposite way. If the Program.Main method included a line
such as this:

Console.WriteLine(theGreeting.Recipient);

then the program would write "Eric" on the console. The get accessor returns the value
of the _recipient member variable.
Let’s go back to the earlier question – why go to all the trouble of defining a property
that has the same effect as making _recipient public? The answer is that, by using the
code inside the get and set accessors, you can control access to the _recipient
member variable.
Why would you want this control? Imagine that, at some future point, you want to
prevent the Recipient property from having a certain value (such as an empty string).
By adding some code to the set accessor, you can prevent the caller from assigning this
value to _recipient. Without the property accessor methods, you would have to check
every single time any code, anywhere in your program, wrote a value to the _recipient
member variable.
The use of properties to control access to class data is an example of a concept called
encapsulation. If you remember back to the explanation of what classes are for, you
learned that they add structure to a program by bringing together all the code that
relates to a certain part of the program. As an example of this, by encapsulating the
_recipient member variable inside a property, you have brought all the code that
controls the value of _recipient into a single location, instead of the code being
scattered all around your program. As your programs get bigger, you will find them
much easier to manage when you can design them so that related code is organized in
one place.

Summary
This guide ends just as you have met the fascinating subject of program design, by
building your first class. Along the way, you have learned about methods, data types,
variables, and controlling program flow with conditionals and loops. These are the basic
building blocks of any program. Once you have mastered these tools, you are well on
your way to becoming a fully-fledged programmer.
If you have enjoyed learning how to make a program work, there are many
opportunities for you to take your next steps. This guide has only introduced some of
the more common building blocks, and there are several more for you to discover.
Now that you have learned the basics of the C# programming language, here are some
other concepts to learn about on your own:
• Using other loops and conditionals. You have seen the most commonly-used
loops and conditionals in this guide. You can also learn about do-while loops,
foreach loops, and switch statements.
• Exploring the .NET Framework. Your first program used only the Console
framework class. There are hundreds of classes in the .NET framework that enable
you to do anything from networking with other computers to creating 3-dimensional
games.
• Using arrays and collections. Arrays and collections enable you to work with
groups of objects rather than defining an individual variable for each one.
• Handling exceptions. A program causes an exception when it does something that
it shouldn’t, like dividing by zero. Good programs are prepared for the unexpected,
and can receive notifications of these exceptions so they can take appropriate action.
• Inheritance, interfaces and polymorphism. When you create a class, you can
inherit the behavior of an existing class so that your own class behaves in a similar
way. You can also use interfaces to define what methods and properties a class
should have, so that several different classes can have the same appearance.
• Using Generics. Generics enable you to write ‘generic’ classes, such as collection
classes, that can ensure that you don’t put the wrong type of object into a collection.
The MSDN Web site has many more lessons for you to study as you progress to more
advanced techniques and more complex programs. Happy learning!

Potrebbero piacerti anche