Introduction To CSharp
Introduction To CSharp
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.
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.
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.
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!");
using System;
using System.Collections.Generic;
using System.Text;
namespace MyFirstApplication
class Program
Console.WriteLine("Hello, world!");
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!");
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.
using System;
using System.Collections.Generic;
using System.Text;
namespace MyFirstApplication
class Program
SayHelloWorld();
Console.WriteLine("Hello, World!");
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.
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.
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:
int myInteger;
myInteger = myString;
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.
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.
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
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.
string message;
if (toWhom == "Eric")
else
{
return message;
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.
SayHelloTo(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.
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)
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#.
class Program
...
...
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.
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
public Greeting()
_recipient = "Stranger";
Console.WriteLine(message);
}
}
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:
Greeting theGreeting;
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.
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.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.
class Greeting
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".
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.
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:
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!