1
C# is pronounced as "C
sharp". It is a new programming language that enables programmers in
quickly building solutions for the Microsoft .NET platform.
Today, one cannot, just
cannot, afford to ignore C#. It is our considered opinion that it holds immense
promise and we are going to try our best, through this book, to help you
realize its potential. Be assured, we are not going to teach you just another
programming language. It is our intention to help you apply C# in practical
situations, to actually implement your newly acquired knowledge on the Net.
With this brief introduction,
let us embark on a path that will take you to new adventures in the world of
Internet. In this chapter, we will get you started with C# by introducing a few
very simple programs. For remember, even a journey of a thousand miles must
begin with a single step.
We assume that you have no
prior knowledge of any programming language. But before we get ensnared in the
fascinating world of C#, let's make a directory where we will save all our work.
In order to do so, click on Start, Programs, then go to Accessories and select
Command Prompt (Windows 2000) or the MS-DOS Prompt as it is called in Windows
98. Once you are at the command prompt
create a directory called csharp (md csharp) and change to this directory (cd
csharp). Now type the command 'edit a.cs', which will open the MS-DOS editor -
the world's simplest editor.
C:\csharp>edit a.cs
Yes, we very well understand
how you must be yearning to write your first C# program and get it working. But
before we do that, there are certain intricacies that you must understand. What
a.cs refers to is called the filename or program name. Here we have named our
file or program a.cs. Why a.cs? Well, before we began writing this book, we
consulted a renowned astrologer who predicted that if we named our first file
a.cs then great luck would be showered on us. Not wanting to quarrel with the
stars, we named our file a.cs. But you are free to go ahead and call your file
any name you want. But then do so at your own risk! Remember, forewarned is
forearmed!
Jokes aside, 'cs' is the
extension used for C# files. They say of all the things you wear, your
expression is the most important. Notwithstanding this, one does look more
dapper in a suit rather than a vapid shirt and trousers. Similarly, though it
is not mandatory to provide the extension 'cs', you can make a filename seem
more impressive by giving it an extension. To reiterate, you could have given
the extension say 'ws' too; it does not matter. But absent minded as we are, it
is more prudent to give appropriate extensions while naming files.
As the first step, we will
understand the basic structure of a C# program.
a.cs
class zzz
{
}
Here we start with the word
class zzz followed by open and close curly braces. A class is nothing but a
collection --- a collection of everything that the programming language
contains. It is like a packet or a container, which can hold anything. Hence everything
in a C# program must be enclosed within a class. We have named our class zzz,
again you could have named it anything else but if you would rather follow our
naming convention (for reasons well amplified above!), name it zzz.
Now for the part that you've
been eagerly waiting for!
In order to execute the
program, go to the File menu, and click on Exit. You will get a dialog box
asking you whether you want to save the file or not, say yes. Now that we have
typed and saved our file we need to execute it. The compiler creates executable
code. The command used to call the C# compiler is csc followed by the program
name. Since our program name is a.cs, the command csc a.cs will call the
compiler. A compiler is a program which understands the C# programming
language. Thus the word class is part and parcel of the C# language. Microsoft
lets you freely download the C# compiler from their web site :
http://msdn.microsoft.com/library/default.asp.
Select .Net Framework SDK under .NET Development. Choose the Download
option to download the sdk which is around 127 MB large. Install the product on
your machine cause if you don’t, none of the following programs will work.
Also, Internet Explorer 5.5 and Microsoft Data Access Components(2.7) must be
installed prior to installing the sdk
Once done, type the command
as follows:
C:\csharp>csc a.cs
You will see the following
output on your screen in the dos box.
Microsoft (R) Visual C# Compiler Version 7.00.9254 [CLR
version v1.0.2914] Copyright (C) Microsoft Corp 2000-2001. All rights reserved.
error CS5001: Program ‘a.exe’ does not have an entry point
defined
Just as the excitement was
beginning to grow, our program returns with an error message. Don't worry,
occasional failure is the price of improvement.
The error message starts with
an error number CS5001 followed by a cryptic message, which we do not
understand.
We are aware of the fact that
everything has a beginning and an end. Similarly, a C# program also has a start
and an end. Ah! Now you realize why the error occurred. We forgot to tell C#
where to start executing our program from. This starting point is also called
an entry point.
You can specify the entry
point by adding static void Main() to your program, just as we have done below.
a.cs
class zzz
{
static void Main()
{
}
}
Compile the above code giving
the command as csc a.cs. Voila! Now no
errors.
The compiler will now
generate an exe file called a.exe. Giving the command dir at the command prompt
will prove the same. On keen observation you will notice that among the 2 files
listed, there is a file by the name a.exe. Simply type 'a' at the command
prompt, your program will now be executed!
C:\csharp>a
The program will run but
shows no output on our screen. But, at least we get no errors.
The words, static and void,
will be explained to you a little later, in the right perspective. Thus if you
had felt the beginnings of a massive headache, you can breathe easy! Anything
followed by '(' and ')' brackets is
called a function. So, it is obvious that Main is nothing but a function. Here
we are creating a function called Main. It is followed by the '{' and '}' curly
braces. Note that the letter M in Main is capital. Thus C# requires a function
called Main, which is the first function that will be executed. Failure to do
so will result in an error. Ergo, whenever you see a word beginning with an
open '(' and close bracket ')', C# and most other programming languages call it
a function. The { signifies the start of a function and the } signifies the end
of the function. The guys who designed the language decided to use {} braces
instead of start and end. When you tell people that you are learning a
programming language, you are actually learning to use {} braces to specify the
beginning and end of a function. These rules have to be remembered by rote. You
have no choice.
Now we are ready to add some
code in our program. In order to do so, add the line
WriteLine("Hell"), just as we have done below.
a.cs
class zzz
{
static void Main()
{
WriteLine("Hell")
}
}
Oops! The astrologer had
promised showers of luck! Even a drizzle seems far away! Executing the above
program results in the following error:
Compiler Error
a.cs(5,18): error CS1002: ; expected
The error message begins with
the file name, a.cs followed by round brackets containing the line number and
the column number, where the error occurred. The compiler informs us that it
found an error on line number 5 and column number 18 and it expects a ;.
As the cliché goes, when the
going gets tough, the tough get going. So we shouldn't lose heart as yet; let's
understand why this error occurred.
Look at WriteLine within the
brackets; doesn't it ring a bell? Isn't WriteLine a function too? But here we do
not have the curly braces following it. This is because here we are not
creating a function like we created Main. Then what is it that we are doing? We
are calling a function called WriteLine, which has already been created.
The error says ';' expected.
Though it is obvious to us that the statement has ended, unfortunately for you
and me, C# isn't so smart. It requires a semi-colon to tell it loud and clear
that the statement has ended. Merely pressing enter does not suffice. Though
not so for other programming languages, in C# it is mandatory to use a
semi-colon. Alas! Each programming language has its own rules!
At this juncture, an
intelligent question would be - But why semi-colon? Why not any other
punctuation mark? We don't know for sure but perhaps the developers of C# were
asked to select a character that would indicate the end of a statement. The
non-compromising species that we are, they could not arrive at a
consensus. Result? Grandma's recipe of
eene meene mina mo! When they stopped, their finger was pointing at the
semi-colon, hence they selected the same.
Thus rules are rules; as
preposterous as they may sound, they must be followed.
Add the semi-colon and
execute the program. Also languages like ABAP/4 from SAP ends lines with a dot
(full stop). Thus we expect to understand programming in English. Every
language expects an end of statement/command terminator. Every language expects
a symbol to denote when the user has finished saying something. In C# it is a ;
, other languages have their own symbols. Remember that the statement or
function WriteLine was written on line number 5 hence the error reported line
number 5.
a.cs
class zzz
{
static void Main()
{
WriteLine("Hell");
}
}
Compiler Error
a.cs(5,1): error CS0103: The name 'WriteLine' does not exist
in the class or namespace 'zzz'
Another error! We are
extremely disappointed, it just doesn't seem our day. However we firmly believe
that you may be disappointed if you fail, but are surely doomed if you don't
try. And we don't want to be doomed do we? So let's keep our chin up and carry
on.
But you know what's most
irritatingly bothersome? Why are all error messages so difficult to understand?
Well, with the experience that we have gained over the years we have learnt
that if error messages could be understood then we wouldn't get them in the
first place!
In any case, to be truly
candid, the error occurred because we pulled a fast one on you! We are calling
a function WriteLine but in fact no such function exists. The accurate name of
the function is not WriteLine but System.Console.WriteLine. Microsoft is known
to fancy big names and here is one more example. In any case, let's execute the
program.
a.cs
class zzz
{
static void Main()
{
System.Console.WriteLine("Hell");
}
}
Output
Hell
Finally, no errors! Surely
you feel blessed! It displays the word 'Hell', and we suspect that's exactly
what you are going through right now. But if you follow our programs step by
step we assure you that heaven is not too far away.
Now remove all the extra
spaces and 'enters' from your program, just as we have done below and compile
the program again.
a.cs
class zzz {static void Main()
{System.Console.WriteLine("Hell");}}
Output
Hell
You will notice that doing so
does not give any errors. Just like the previous program, it displays 'Hell'.
The C# compiler is not affected by it. But using spaces and 'enters' definitely
make your program neater and thereby more readable. The effect is especially
appreciated in large programs and more so when someone else has to go through
them. Having said that, anyway, the first thing that C# compiler does is
removes all the spaces and enters from the program code you have written.
In the next program, we have
called WriteLine function twice.
a.cs
class zzz
{
static void Main()
{
System.Console.WriteLine("Hell");
System.Console.WriteLine("Bye");
}
}
Output
Hell
Bye
On executing this program,
'Hell' and 'Bye' are displayed on two separate lines. Here, we are not required
to give anything that has the 'enter' effect, WriteLine automatically prints on
a new line each time. Which simply means you can call a function as many times
as you like.
In the next illustration,
let's understand how functions are called and created. Here we are calling a
function abc().
a.cs
class zzz
{
static void Main()
{
abc();
}
}
Compiler Error
a.cs(5,1): error CS0103: The name 'abc' does not exist in
the class or namespace 'zzz'
On executing this program you
will get, what else, but an error. Peter Drucker, the famed management guru had
once said that the better a man is, the more mistakes he will make, for the
more new things he will try. So there you go - next time you encounter an
error, simply tell yourself that you have just become better at whatever you
are doing.
In any case, the error says
that abc does not exist. Here we are calling a function called abc(), but where
is abc() defined or created ? It is not a function that has been provided by C#
to us free of charge. It is our own homegrown function that we are calling. The
lesson here is that we cannot call a function without first creating it. So, to
rectify this error we will first create a function abc. Our next example
demonstrates this.
a.cs
class zzz
{
static void Main()
{
abc();
}
static void abc()
{
System.Console.WriteLine ("Hell");
}
}
Output
Hell
In the function abc, we have
included only one statement- WriteLine within the curly braces. The '{' and '}'
braces indicate the beginning and the end of this function. Alternatively, a
function can contain millions of lines of code that will be executed when the
function is called. Since everything is contained in a class, our function abc
is also created within the class zzz but outside Main. But the function is
called from Main. On executing the program, 'Hell' is displayed. This is
because we have included the code for 'Hell' to be displayed in the function
abc. Thus, when the control reaches the line abc(); it searches for that
function and executes the code within that function. We will explain static and
void later as promised.
You can call as many
functions as you like from your program. But you must remember to separate each
one with a semi-colon. The next program illustrates this.
a.cs
class zzz
{
static void Main()
{
abc();
pqr();
abc();
}
static void abc()
{
System.Console.WriteLine ("I am ABC");
}
static void pqr()
{
System.Console.WriteLine ("I am PQR ");
}
}
Output
I am ABC
I am PQR
I am ABC
At first the function abc is
called, then pqr and then again we are calling abc. On executing this
program 'I am ABC', 'I am PQR' and 'I
am ABC' will be displayed. This is because
we have included the code for these lines to be displayed in the respective
functions.
In the following program we
are calling the function pqr from abc and not from Main.
a.cs
class zzz
{
static void Main()
{
abc();
}
static void abc()
{
pqr();
System.Console.WriteLine ("I am ABC");
}
static void pqr()
{
System.Console.WriteLine ("I am PQR ");
}
}
Output
I am PQR
I am ABC
In the function abc, we are
first calling pqr and then displaying 'I am ABC' using the WriteLine function.
Hence, first 'I am PQR' is displayed and then 'I am ABC'. Thus, this program demonstrates
how functions can be called from other functions.
Now that we have created our
own functions abc and pqr, we have an intuitive understanding of how C# created
the function System.Console.WriteLine. The next program uses the printing or
formatting capabilities of the WriteLine function.
a.cs
class zzz
{
static void Main()
{
System.Console.WriteLine("100 {0}",100);
}
}
Output
100 100
The zero in the curly braces
means that after the first comma there is some value and that it should display
this value. You cannot differentiate between the two 100's. The {0} is replaced
with 100, the number, which follows the first comma. If you don't like the
number 100, use the number 420 instead. We won't mind - at least it's something
that some of you can easily identify with!
The program below is simply
an extension of the above.
a.cs
class zzz
{
static void Main()
{
System.Console.WriteLine("100 {0},{1}",100,200);
}
}
Output
100 100,200
Here the {0} is replaced with
100 and {1} is replaced with 200. The comma (,) separates the two numbers. Thus
{0} means the first number and {1} means the second. C# likes to count from
zero and not one.
a.cs
class zzz
{
static void Main()
{
ii;
ii=20;
System.Console.WriteLine ("{0}",ii);
}
}
Compiler Error
a.cs(5,1): error CS0201: Only assignment, call, increment,
decrement, and new expressions can be used as a statement
a.cs(5,1): error CS0103: The name 'ii' does not exist in the
class or namespace 'zzz'
a.cs(6,1): error CS0103: The name 'ii' does not exist in the
class or namespace 'zzz'
a.cs(7,33): error CS0103: The name 'ii' does not exist in
the class or namespace 'zzz'
Experience is knowing a lot
more of things you shouldn't. But now that you have decided to embark upon this
book, let's see what you should know!! Executing this program results in a
large number of errors as shown above. Let's understand the rationale behind
it. Here we have included a strange word --- ii. This word ii is being given a
value of 20 as ii=20. But C# is a shy program. It does not speak to strangers!
Here ii is nothing but a stranger to C#. C# does not know who or what ii is.
You can't just write words that you feel good about. So, in order to rectify
this error we must tell C# who ii is.
Our next program will
demonstrate how this can be done.
a.cs
class zzz
{
static void Main()
{
int ii;
ii=20;
System.Console.WriteLine ("{0}",ii);
}
}
Output
20
Note that in this program we
have added the word int before ii. The word int indicates that ii is an integer
or a number. Each time we create our own word like ii, C# wants to know what we
will store in this word. We will understand this better and in totality in just
a little while. Here we are initializing ii to 20 or giving it a value of 20 by
writing ii = 20. Why 20? Maybe because we are feeling very youthful today! Following this we have the WriteLine
function. Now, it is a known fact that jaggery is a good substitute for sugar.
Similarly, in C# you can substitute a number with a word. So, in WriteLine we
have used the word ii instead of a number. The word ii gets replaced with the
value 20. So, on executing the program, the number 20 is displayed.
You may be wondering as to
why should you ever use a word when you can use a number directly. Our next
program will enlighten you on this.
a.cs
class zzz
{
static void Main()
{
int ii;
ii=20;
System.Console.WriteLine ("{0}",ii);
ii=30;
System.Console.WriteLine ("{0}",ii);
ii=ii+10;
System.Console.WriteLine ("{0}",ii);
ii=ii+1;
System.Console.WriteLine ("{0}",ii);
ii++;
System.Console.WriteLine ("{0}",ii);
}
}
Output
20
30
40
41
42
The first three lines of this
program are identical to those of our previous one. Thus in the first, the
WriteLine function will display the number 20. Thereafter, by saying ii=30 we
are initializing the word ii to a value 30. In effect, we are changing the
value of ii from 20 to 30. So, WriteLine will now display 30.
For conceptual understanding,
we earlier introduced ii as a word. However, in the software world, it has
another name; it is actually called a variable.
Thus, a variable is a word
whose value varies or changes. ii initially had a value 20 that changed to 30.
Coming back to what the word
int means- when you say int, int means integer or number. When we say int ii,
it means that the variable ii will store a number. ii could also be used to store
the letters of the alphabet like the names of people. It could also store a
date. But here we wanted ii to store a number. So, we have to tell C# in
advance as to what the variable is going to store. Hence we say int ii. C#
understands the word int as int is a part of the C# programming language.
The variable ii started with
the value 20 and is now holding a value 30. In the next line we have ii=ii+10.
The 'equal to' sign makes this statement look complicated. To avoid confusion,
always start by looking to the right of the 'equal to' sign. To the right of
the equal to sign we have ii+10. Since ii is holding the value 30, ii+10 is
read as 30+10, which evaluates to 40. Hence ii=ii+10 will now be read as ii=40.
This value 40 is given to the variable on the left-hand side. Now that ii has a
value 40, WriteLine will display 40. Similarly, we say ii=ii+1. Here the value
of ii is incremented by one. And the new value of ii, which is 41 will be
displayed by WriteLine. In the next line we have ii++. Note that ii=ii+1 and
ii++ do the same thing. They both increment the value of ii by 1. Hence
WriteLine will now print the number 42.
This is a big problem with
programming languages. As there are many ways to skin a cat, there are also
many ways to increase the value of a variable. So ii = ii + 1 and ii++ do the
same thing.
A programmer thus has the
choice to use either of the two ways to do the same thing. There you go ---as
you can see, first time programmers have unfortunately a lot to learn.
In daily life, a hundred
different people can do the same chore in a hundred different ways. Similarly,
in programming there is more than one way of doing a particular thing.
Programming becomes a problem because of redundancy. Since there are two ways
of doing the same thing you have to learn them both and that can be very
confusing. Of course, it is at your discretion to choose the method you are
comfortable with. Henceforth, even though there may be many other ways of doing
a particular thing, we will teach you only one method that we find appropriate.
A variable is a word that
stores a value. This value can be changed at will by the programmer. Wherever
we can use a number, we can also use a variable.
The next program may seem
alien to you. This is because it speaks the truth. If it finds that a condition
is true it outputs true and if it finds the condition to be false it outputs
false. Very unlike some of you, who would do just the opposite!
a.cs
class zzz
{
static void Main()
{
System.Console.WriteLine ("{0}", 5 > 2);
System.Console.WriteLine ("{0}", 5 < 2);
System.Console.WriteLine ("{0}", 2 < 2);
System.Console.WriteLine ("{0}", 2 <= 2);
System.Console.WriteLine ("{0}", 2 != 2);
System.Console.WriteLine ("{0}", 2 !=3);
}
}
Output
True
False
False
True
False
True
Let's understand this program
line by line as usual.
Here the first line says
WriteLine("{0}", 5 > 2); Is 5 > 2 ? Yes. So the condition 5
> 2 evaluates to true. Hence the {0} in WriteLine is replaced with True and
the WriteLine function displays True. 5 > 2 is called a condition. A
condition is like a question which has to result in a yes or no or a true or
false. In this case the number 5 is greater than the number 2 and hence the
function evaluates to true. C# understands the words true and false.
In the second WriteLine we
have the condition 5 < 2. Is 5 < 2? No. So the condition 5 < 2
evaluates to false and hence WriteLine displays False. Similarly, the next
condition 2 < 2 is not true and hence False is displayed.
In the next statement we have
2 <= 2. Here the first sign being '<' it is first checked whether 2 <
2? No, 2 is not less than 2. So then the second sign '=' is checked i.e.,
whether 2 = 2? Yes. So the condition 2 <= 2 evaluates to true and WriteLine
displays True. <= is thus two conditions in one .
In the next WriteLine we have
the condition 2 != 2. '!=' means 'not equal to'. But 2 is equal to 2, hence the
condition evaluates to false and False is displayed. The comparison is false, therefore the condition is false.
In the last statement we have
the condition 2 != 3. Is 2 != 3? Yes 2
is not equal to 3, so the condition evaluates to true and True is displayed.
This True and False is a special data type in C#. It is called 'Bool' or
boolean derived from Boolean algebra.
a.cs
class zzz
{
static void Main()
{
bool ii;
ii=true;
System.Console.WriteLine ("{0}", ii);
ii=false;
System.Console.WriteLine ("{0}", ii);
}
}
Output
True
False
In our previous programs we
used the data type int for the variable ii. This meant that ii could store
integers or numbers. Similarly, you can now initialize ii to either true or
false. This is possible by using the data type bool for ii. A data type means
the type of data a variable can hold. Therefore, here we are saying bool ii. In
the first case we are initializing ii to true. So in WriteLine, {0} is replaced
with true. In the second case ii is initialized to false and {0} is replaced
with false.
In a gist, we now know that
variables can be either bool or logical or they can contain the words True or
False. Also, variables can also contain numbers.
Let's see how C#
distinguishes between data types.
a.cs
class zzz
{
static void Main()
{
bool ii; int jj;
ii=10;
jj=false;
}
}
Executing the above program
gives the following errors:
Compiler Error
a.cs(6,4): error
CS0031: Constant value '10' cannot be
converted to a 'bool'
a.cs(7,4): error
CS0029: Cannot implicitly convert type
'bool' to 'int'
If you want the rainbow,
you gotta put up with some rain. So let’s understand the reason behind the
errors. Here C# is internally saying that it distinguishes between data types.
In that sense C# is very petty about what values you give to variables. Bool can't
mix with int and vice versa. Since ii is a bool you can't initialize it to 10,
which is a number. C# is very strict about this. And because jj is an int you
can't initialize it to false. So you have to be very careful about how you
initialize your variables. After all it doesn't make sense to ask someone who
is good at driving to teach computers and vice versa. Everyone has his or her
place in life. Similarly, variables also have their place. Hence a variable
declared as a bool can only have values true or false. Similarly, int can have
only numbers or integers, it cannot take true or false values.
Our next program is similar
to one of the previous programs.
a.cs
class zzz
{
static void Main()
{
bool ii;
ii=6 < 7;
System.Console.WriteLine ("{0}", ii);
}
}
Output
True
Here ii is a variable of type
bool. In the next statement we have ii = 6 < 7. As you already know, in such
a case you should start by looking to the right of the 'equal to sign'. Because 6 is less than 7 the condition
evaluates to true and ii will be initialized to true. Hence {0} is replaced
with the value of ii, which is true and True is displayed.
C# is called a strongly typed
language because you cannot initialize a variable of type int to a variable of
type bool. The reason C# is very strict about this is because this system
eliminates a large number of sloppy programming errors. Some languages like C
on which C# is based on do not care what values you initialize your variables
to. C# is stricter than even Java. In some ways, it's like your mother when it
comes to telling you what you are doing wrong in life. Thus it is extremely
difficult to make dumb errors in C#. Remember when you are writing code in C#,
the compiler is always peering down your shoulder making sure you do not get
away with any errors.
If Statement
So far the code that we have
written is rather useless. This is because it always gets executed. Life is
enjoyable only because it is unpredictable. We don't know what tomorrow is
going to bring. Variety is the spice of life! Similarly, we would like to write
computer programs, which add spice to programming. We want to write programs
that behave differently depending upon different situations or circumstances.
And this can be achieved with the help of the if statement. So fasten your
seatbelts and get set to ride!
The next few programs will
demonstrate the usefulness and application of the if statement.
a.cs
class zzz
{
static void Main()
{
if ( false )
System.Console.WriteLine ("Hi");
}
}
Compiler Warning
a.cs(6,1): warning CS0162: Unreachable code detected
In this program we have
included the word 'if' followed by false in round brackets. This is the if
statement and its syntax. Syntax is the grammar in writing. Thus we have no
choice but to abide by the rules. It is called a statement because anything
that C# recognizes is called a statement. When you run this program, you realize
that there is no output. So this program will simply display nothing. Now you
know why we get the above warning as our code will never get executed.
Let's understand the
rationale behind it.
The if statement lets you
include decision making in your program. It decides whether to execute the next
line or not. When the if statement evaluates to false then the next line is
ignored. The if statement brings with it the power to decide whether certain
code should be executed or not.
The following program will
make this concept clearer.
a.cs
class zzz
{
static void Main()
{
if ( false )
System.Console.WriteLine ("Hi");
System.Console.WriteLine ("Bye");
}
}
Output
Bye
The if statement looks at the
immediate next line, it doesn't look at the line after that. Since the if
statement influences only one line, you will see only Bye displayed and not Hi.
Same warning again.
But if you want both the
statements to be affected by the if then enclose them within curly braces. This
is illustrated below.
a.cs
class zzz
{
static void Main()
{
if ( false )
{
System.Console.WriteLine ("Hi");
System.Console.WriteLine ("Bye");
}
}
}
Here we have included both
the lines of code within the braces. Now the if statement will affect both the
lines of code. The condition being false, nothing is displayed. Thus, the if
statement gives us the option to execute or not to execute a certain piece of
code.
If we always use false then
the code will never be called. But what did we tell you about conditions? They
return either true or false. So, in the next program we have 3 > 8 as the
condition. Since 3 is not greater than 8 the condition evaluates to false.
Since there are no curly braces, only the next line is affected by the if
statement. Hence only Bye is displayed.
a.cs
class zzz
{
static void Main()
{
if ( 3 > 8 )
System.Console.WriteLine ("Hi");
System.Console.WriteLine ("Bye");
}
}
Output
Bye
Let's look at another
variation of this program. Now, the interesting part is that wherever you can
use a condition you can also use a variable which is of type bool, which we
know evaluates to either true or false.
a.cs
class zzz
{
static void Main()
{
bool ii;
ii=true;
if ( ii )
{
System.Console.WriteLine ("Hi");
System.Console.WriteLine ("Bye");
}
}
}
Output
Hi
Bye
Here the variable ii is
declared as a bool and then initialized to true. In the next line we have if
(ii). The variable ii holds the value true and hence the if condition evaluates
to true. The condition being true both Hi and Bye are displayed. Note that here
both the statements are included in the curly braces resulting in both the
statements being affected by the if statement. Thus the if statement is
affecting a block of statements. Declaration is another way of saying that we
are creating a variable.
In the following program we
have an if with the else. If the if condition evaluates to true then the
statement following it is called but if it evaluates to false then the else is
called.
a.cs
class zzz
{
static void Main()
{
if ( false )
System.Console.WriteLine ("Hi");
else
System.Console.WriteLine ("Bye");
}
}
Output
Bye
Here, since the condition
evaluates to false the else is called and hence Bye is displayed. Thus the
additional else statement specifies a statement that is executed when the
condition is false. This construction covers all possibilities, as a condition can
be either true or false. In an 'if-else' construct one of them have to be
executed. Computer programs are said to be made intelligent because of the if
statement. The more the use of the if statement, the more intelligent your
program becomes. The if statement is one of the main building blocks of any
programming language. Thus all programming languages have to have a if
statement.
Loops
The if statement is the
cornerstone of programming because it lends intelligence and a decision making
power to the language. The second important constituent of any programming
language is a looping construct. In a program many times you would need to
repeat instructions. In C#, the for statement is one form of a loop that lets
you repeat statements. However, as we already know, a statement can also be a
block of statements, thus it also allows repetition of multiple statements.
Our next program explains the
for loop.
a.cs
class zzz
{
static void Main()
{
int ii;
for ( ii = 1; ii <= 5; ii++)
System.Console.WriteLine ("Hi {0}", ii);
}
}
Output
Hi 1
Hi 2
Hi 3
Hi 4
Hi 5
The for has 2 semicolons as
part of its syntax or rules. The statement up to the first semicolon is
executed only once. For the first time and only the first time ii is
initialized to 1. Remember up to the first semicolon the statement is executed only once. The statement enclosed
within the first and second semicolon is a condition. The condition checks
whether ii <= 5 evaluates to true. Since this condition evaluates to true,
the statement within the open and the close braces gets executed. If the condition
evaluates to false, the statement is ignored and the loop terminates. The
variable ii has a value 1 which is less than 5, so System.Console.WriteLine
will be called which displays 'Hi 1' as the value of ii is 1. After the
statement gets executed, the last part of the for i.e. from the second
semicolon to the closing bracket gets executed. ii++ will increase the value of
ii by 1, making it 2. The condition is checked again, is 2 <= 5. The answer
here is true, so 'Hi 2' is displayed. And this roller coaster goes on till the
condition is false. When ii has the value 6, the condition checked is, is 6
<= 5. The answer being false, the for terminates. This is how the for
statement enables the repetition of code.
Our next example will further
help to illustrate this.
a.cs
class zzz
{
static void Main()
{
int ii;
for ( ii = 1; ii <= 5; ii++)
System.Console.WriteLine ("Hi {0}", ii);
System.Console.WriteLine ("Hi {0}..", ii);
}
}
Output
Hi 1
Hi 2
Hi 3
Hi 4
Hi 5
Hi 6..
In this program we have two
WriteLine statements. The for loop follows the same rules as the if statement.
Thus in absence of curly braces the for loop will affect only the immediate
next statement. Therefore, the for loop will print numbers from 1 to 5 along
with hi. The moment the for loop terminates, ii with the dots will print Hi
6... This goes to prove that when ii has a value six, the for loop will
terminate.
The following program
demonstrates how the for loop enables repetition of multiple statements.
a.cs
class zzz
{
static void Main()
{
int ii;
for ( ii = 1; ii <= 5; ii++)
{
System.Console.WriteLine ("Hi {0}", ii);
System.Console.WriteLine ("Hi {0}..", ii);
} } }
Output
Hi 1
Hi 1..
Hi 2
Hi 2..
Hi 3
Hi 3..
Hi 4
Hi 4..
Hi 5
Hi 5..
Here, both the WriteLine statements
are enclosed within curly braces. Therefore, both the statements are affected
by the for loop. Hence, in this case, each number is displayed twice along with
Hi, once without the dot and once with the two dots.
Similar to the for loop is
the while loop.
a.cs
class zzz
{
static void Main()
{
int ii;
ii=1;
while ( ii <= 5 )
{
System.Console.WriteLine ("Hi {0}", ii);
}
}
}
The while loop takes a
condition, hence the variable ii is initialized to 1 before entering the loop.
The condition checks whether ii <= 5 evaluates to true. Currently the value
of ii is 1. The condition evaluates to true and the statement within the curly
braces is executed. System.Console.WriteLine is called with Hi and the value of
ii. Note that here we are not changing the value of ii within the loop. Since
the value of ii remains 1 the condition always evaluates to true and the loop
will go on forever, indefinitely.
We can't have anything go on
forever, can we? There has to be a stop to it somewhere! Our next program will
resolve this problem.
a.cs
class zzz
{
static void Main()
{
int ii;
ii=1;
while ( ii <= 5 ){
System.Console.WriteLine ("Hi {0}", ii);
ii++;
}
}
}
Output
Hi 1
Hi 2
Hi 3
Hi 4
Hi 5
This program is similar to
the previous one. The only change that we have made is that we added the line
ii++; thus for the first time Hi 1 is displayed. Then the moment ii++ is
encountered the value of ii is incremented by 1, making it 2. Then the condition,
2 <= 5, is checked. The condition being true, once again we enter the loop
and Hi 2 is displayed. This will go on until ii becomes 6. Once ii is 6 the
condition evaluates to false and the loop terminates.
Your mind may ponder over the
question, "Should I use a for or a while?' The for loop is similar to the
while loop. To answer your question in the most simple manner "On Mondays,
Wednesdays, Fridays use for and on Tuesdays, Thursdays, Saturdays use while.
Sundays we assume no one writes code". Alternatively "Toss a coin,
heads use while, tails don't use for" ;-)
In other words, it is at your
discretion to use the one you are comfortable with. Once again C# offers you
multiple ways of doing the same thing.
The Return statement
Let's understand the return
statement with our next example.
a.cs
class zzz
{
static void Main()
{
int ii;
ii = abc();
System.Console.WriteLine("hi {0}",ii);
}
static int abc()
{
System.Console.WriteLine("abc");
return 100;
}
}
Output
abc
hi 100
In this program, at first, ii
is declared as a variable of type int. Then we start
executing the line ii=abc();
Doesn't the right hand side of the statement ring a bell? Aren't we calling the
function abc() ? Hence at this point the control passes to the function abc().
In the function we have the
WriteLine statement, which prints 'abc'. Thereafter, we have a return
statement. It says return 100. In effect, the function abc() is returning a
value 100. Thus the statement ii = abc(); will now be read as ii=100. Now that
ii has a value 100, {0} in WriteLine is replaced with 100 and in turn 100 is
displayed.
a.cs
class zzz
{
static void Main()
{
int ii;
ii = abc();
System.Console.WriteLine("hi {0}",ii);
}
static void abc()
{
System.Console.WriteLine("abc");
return 100;
}
}
Compiler Error
a.cs(6,6): error CS0029: Cannot implicitly convert type
'void' to 'int'
a.cs(12,1): error CS0127: Since 'zzz.abc()' returns void, a
return keyword must not be followed by an object expression
Executing the above program
results in errors. Here we have static void abc(). What static means, we will
explain a little later. It is with the intention to enable you to learn better,
so please bear with us. The word void means nothing. So by saying void abc() we
are saying that the function abc() does not return any value. Functions
may/maynot return values. Earlier abc returned an int. When a function returns
void as in this case, we are saying that abc cannot return a value. But in the
function code we have written return 100. Therefore, because of this
contradiction we get the error. Note that in the previous program we did not
get an error. This was because we had said static int abc(). Here int signifies
the return type of the function. Since the function returns a number we used
int.
In our next example we have
made only one addition i.e. we have added
System.Console.WriteLine("Finish"); after the return statement.
a.cs
class zzz
{
static void Main()
{
int ii;
ii = abc();
System.Console.WriteLine("hi {0}",ii);
}
static int abc()
{
System.Console.WriteLine("abc");
return 100;
System.Console.WriteLine("Finish");
}
}
Compiler Warning
a.cs(13,1): warning CS0162: Unreachable code detected
Output
abc
hi 100
On executing this program,
you will find that the output is the same as the previous program. To your
amazement you do not see the word 'Finish' displayed. No, it is not because C#
doesn't like you. The reason is that anything after the return statement is
ignored.
Thus, you may have a hundred
WriteLine statements after the return statement but they will all be ignored.
Simply stated, no lines after return statement will get called. That is why the
C# compiler, courteous as it is, gives you a warning and not an error.
More on data types.......
You have already learnt about
two data types, int and bool. Our next program introduces a new data type
'string'.
a.cs
class zzz
{
static void Main()
{
string s;
s= "hell";
System.Console.WriteLine(s);
}
}
Output
hell
In this program, the variable
s is declared as a string. This implies that s will store mainly letters of the
alphabet. Then s is initialized to hell, which is nothing but a collection of
the letters of the alphabet. Note that all strings have to be enclosed within
double inverted commas. System.Console.WriteLine displays the value of the
variable s, which is 'hell'. Earlier we wrote a string in double inverted
commas directly. However, this time we are using a variable name instead.
Now we know the first
parameter to the WriteLine function is a string. We earlier named our variable
ii and now we have called it s. Actually, we name our variables depending upon
the time we write our programs. You decide your own rules for naming variables.
Anything you enclose in double quotes is called a string.
System.Console.WriteLine is smart enough to display strings, bools and int.
Let's look at another
variation of the above program.
a.cs
class zzz
{
static void Main()
{
string s;
s= "hell";
System.Console.WriteLine( "{0}", s);
}
}
Output
hell
This program is exactly like
the previous one, the only difference being that we have used {0} instead of writing only s. Here the {0}
is replaced with the value of s, which is 'hell'. Thus, using the {0} is
preferable as it understands a large
number of data types and how to display their values.
Consolidating, our next
example incorporates all the data types that we have learnt so far.
a.cs
class zzz
{
static void Main()
{
string s;
int ii;
bool jj;
ii=10;
jj=false;
s="hell";
System.Console.WriteLine("{0} {1} {2}", ii, jj, s);
}
}
Output
10 False hell
Here the variable s is
declared as a string. Then ii is declared as int and jj is declared as bool. In
the next three statements we are initializing each of the variables. ii is
initialized to 10, jj is initialized to false and s is initialized to hell.
Now, with the help of a single WriteLine statement we are displaying the values
of all the variables. {0} is replaced with 10, {1} is replaced with False and {2} is replaced with hell. This
goes to prove that all the data types can be displayed together, in a single
WriteLine statement. Thus, C# allows all the data types to co-exist in harmony.
Now only if the people of our country could do the same!
Passing parameters to functions
By now you are familiar with
functions and how functions are called. The next program illustrates how
parameters are passed to functions.
a.cs
class zzz {
static void Main()
{
abc(10,false,"hell");
}
static void abc(int i, bool j, string s)
{
System.Console.WriteLine("{0} {1} {2}", i,j,s);
}
}
Output
10 False hell
We have again used the
System.Console.WriteLine function to display values of variables or merely
display text onto the screen. To have it print something on to the screen, we
had to give it the things that we wanted printed. These things are nothing but
parameters. We don't pass things to functions; we pass parameters to functions.
So far we never created our own functions with parameters.
In this program, we are
calling the abc function with three things, with three parameters. The first is
a number, the second is a logical value and the third is a string. So, we are
passing the values 10, false and hell to the function abc(); These values must
be stored somewhere, but where? When we create the function abc we have to
state the names of three variables along with their respective data types. This
is because the values that we pass will be stored in these variables. Hence we
have the variables i, j and s. These are then displayed using WriteLine.
Therefore, it will output 10, False and hell. This is how parameters are passed
to functions in C#. Remember you decide what names to give to variables.
Parameters passed to functions are also variables.
a.cs
class zzz {
static void Main()
{
abc(10,false);
}
static void abc(int i, bool j, string s)
{
System.Console.WriteLine("{0} {1} {2}", i,j,s);
}
}
Compiler Error
a.cs(4,1):error CS1501: No overload for method 'abc' takes
'2' arguments
On compiling this program you
will encounter the above error. Here we are calling abc with only two
parameters, 10 and false. Whereas the function abc is actually created with
three parameters. We are passing an erroneous number of parameters, hence the
error. Lesson? One must pass the same number of parameters that the function
has been created to accept. A mismatch between the number of parameters being
passed and those being accepted will definitely assure you of an error. Thus as
before, C# does a large number of error checks on your code. For, if it allowed
the above function call to go ahead, what would the value of the third
parameter s be?
Now change the order of the
values that are being passed. Your abc function should look like this-
abc("hell",10, false);
a.cs
class zzz
{
static void Main()
{
abc("hell",10,false);
}
static void abc(int i, bool j, string s)
{
System.Console.WriteLine("{0} {1} {2}", i,j,s);
}
}
Compiler Error
a.cs( 5,1): error cs1502: The best overloaded method match
for 'zzz.abc(int, bool, string)' has
some invalid arguments
a.cs( 5,5 ): error cs1503: Argument '1': cannot convert from
'string' to 'int'
a.cs(5,12): error cs1503: Argument '2': cannot convert from
'int' to 'bool'
a.cs(5,15): error cs1503: Argument '3': cannot convert from
'bool' to 'string'
On executing this program you
will be faced with the above errors. These errors have resulted due to a data
type mismatch. It is somewhat like putting a round pole in a square peg! How is
it going to fit?
While calling the function
abc() the first parameter that we are passing is the word "hell". But
the function abc() has been created to accept the first parameter as an int.
Remember we told you, not so long ago, that C# distinguishes between data
types. Thus you can't store a string in a variable of type int. Similarly, the
value 10 cannot be stored as a bool and false cannot be stored as a string.
Therefore, not only should the number of parameters being passed and accepted
be the same but also their data types must match.
Like oil and water do not
mix, in the same way you cannot give C# an int when it wants a string. As said
earlier, some languages are more forgiving then C# due to which the programmer
makes more mistakes in them.
a.cs
class zzz
{
static void Main()
{
abc();
}
}
class yyy
{
static void abc()
{
System.Console.WriteLine("abc");
}
}
Compilation Error
a.cs(5,1): error CS0103: The name 'abc' does not exist in
the class or namespace 'zzz'
Seems like we are hooked on
to errors!
In this program we have
created another class called yyy. We can have as many classes in one .cs file
as we like. This program now has two classes, zzz and yyy. The class zzz has a
function called Main. Main denotes the starting point of our code and as such
is the first function to be called. The class yyy contains a function called
abc. Here we are calling the function abc by saying abc(); in class zzz. But
class zzz does not have any function by the name abc. Merely giving abc();
encourages C# to assume that abc() exists within the class zzz. But our abc
function is contained in yyy. Hence we get an error as we are trying to call a
function that exists in another class.
But we are adamant! We want
to use the abc function that yyy has. It's human tendency to want things that
others have! So, in the next program we are calling the function abc in the
class yyy by writing yyy.abc();
a.cs
class zzz
{
static void Main()
{
yyy.abc();
}
}
class yyy
{
static void abc()
{
System.Console.WriteLine("abc");
}
}
Compilation Error
a.cs(5,1): error cs0122: 'yyy.abc() is inaccessible due to
its protection level.
When we say yyy.abc(); why
the dot? yyy is the name of the class and abc() is the name of the function .
Each of these names can be as large as you want, so to separate them a dot is
used. Thus when you want to access a function that belongs to another class you
can do so by specifying the class name and function name separated by a dot.
The dot is like the semicolon. The designers of the language wanted some
character as a separator between class name and function name, they chose the
dot, they could have also chosen the semicolon again.
You will now realize why we
say Console.WriteLine. Obviously, it means that Console is a class and within
the class Console there is a function called WriteLine.
But to your dismay, on
executing this program you still get an error. Well, few people get what they
want, however fewer still want what they get! You may want a particular thing
but you will not get it unless the other party gives you the permission to take
it, use it or share it. Your only other option is to put up a fight!
We get an error here because
we haven't used the word public. The whole idea behind C# is its usability on
the net. And the only way you can use it on the net is by having security
precautions. So in C# the default rule is - you can't use anything unless
explicitly granted permission. Next question. How do you grant the necessary
permission?
Being its non-violent self,
C# grants permission by using the word public. When we say public, we mean the
world at large. So by starting with the word public we are saying that the
whole world is now allowed to use this function as we are explicitly granting
you rights. If you don't use the word public it will give you an access error.
To rectify the error, add the
word public just as we have done below.
a.cs
class zzz
{
static void Main()
{
yyy.abc();
}
}
class yyy
{
public static void abc()
{
System.Console.WriteLine("abc");
}
}
Output
abc
Finally, we have the correct
code! See, one of life's greatest ironies is the fact that when you finally
master a tough job, you make it look easy!! By using the word public in front
of the function abc, we can now call it from zzz by specifying yyy.abc(); Now
that the function is called, WriteLine displays 'abc'.
Our next example will enhance
your understanding further.
a.cs
class zzz
{
static void Main()
{
yyy.abc();
abc();
zzz.abc();
}
public static void abc()
{
System.Console.WriteLine("abc in zzz");
}
}
class yyy
{
public static void abc()
{
System.Console.WriteLine("abc");
}
}
Output
abc
abc in zzz
abc in zzz
Now we go a step further. In the above program we have two abc functions, one in class zzz and one in class yyy. If you want to call the one in yyy then you say yyy.abc(); but if you want to call the one in zzz then you say zzz.abc() or abc(). The function abc(), by itself, will ask which class is it? Since abc() is in zzz itself, C# assumes it to zzz.abc(); By implication, if the function exists within the same class, it is optional to preface the function with the name of the class. When you execute this program, yyy.abc() will call the abc function in class yyy and WriteLine will display 'abc'. Thereafter, both abc() and zzz.abc() will call the abc function in class zzz. And in each case WriteLine will display 'abc in zzz'. Thus if you do not preface the function name with the name of the class, C# will add the name of the class in which you are calling the function. In our case it is zzz.