Chapter 3 C# Basics
Chapter 3 C# Basics
Chapter 3 C# Basics
C# Basics
This chapter discusses the following topics:
3.1 Identifiers
Identifiers are names used to represent variables, labels, object names, named
constants and functions (methods). An identifier can be 1 to 255 characters long
(although it seldom exceeds 30 characters) and it is formed by combining upper and/or
lower case letters (A to Z, a to z,), digits (0 to 9) and the underscore (_). Special
characters such as @, #, *, ?, period (.) and blank (white space) are not allowed in
an identifier. An identifier must start with a letter and may be followed by one or more
letters, digits or underscores.
Keywords (or reserved words) are predefined reserved identifiers that have special
meanings to the compiler. Keywords cannot be used as identifiers in a program. That
means you should not use words such as Console,For,Switch,WriteLine
and While as identifiers.
The list of keywords in C# is given below.
abstract
as
base
bool
break
event
explicit
extern
false
finally
new
null
object
operator
out
struct
switch
this
throw
true
3-2 Chapter 3
byte
case
catch
char
checked
class
const
continue
decimal
default
delegate
do
double
else
enum
fixed
float
for
foreach
goto
if
implicit
in
int
interface
internal
is
lock
long
namespace
override
params
private
protected
public
readonly
ref
return
sbyte
sealed
short
sizeof
stackalloc
static
string
try
typeof
uint
ulong
unchecked
unsafe
ushort
using
virtual
volatile
void
while
Reason
Date?
Interest rate
Amount$ Payable
123
e.one
@fsktm.um.edu.my
http://www.wcg.org
Contains ?
Contains blank
Contains $ and blank
Starts with a number
Contains .
Contains @ and .
Contains :, / and .
C# Basics 3-3
3-4 Chapter 3
Sumx2
acts of chivalry
1234567
*
false
//
//
//
//
this
this
this
this
is
is
is
is
a string literal
also a numeric literal
character literal
a Boolean literal
There are also literals which have specific meaning. They are called escape sequences
or escape characters. These are useful for input/output whether on the console or
printer. The table below gives the list of these escape sequences.
Escape
sequence
\a
\b
\f
\n
\r
\t
\v
\
\
\\
Character
produced
Meaning
Alert/beep
Backspace
Form feed
New line
Carriage return
Horizontal tab
Vertical tab
Single quote
Double quote
Backslash
C# Basics 3-5
where type refers to data type and var1 to varn are the names of variables
separated by a comma. The semicolon terminates the statement.
The following are some examples of variable declaration:
stringProductCode;
intQuantity;
doublePrice;
decimalAmount;
floatrate;
charch;
intx,y,z;//youcandeclaremorethan1variable
//ofthesamedatatypeinthesameline
You can also assign initial values to variables in a declaration statement as in the
following statements:
charch=a;
intn=20;
doubletotal=0.00;
Constants have fixed values, i.e., their values dont change during the course of
program execution. A constant is declared by using the keyword const followed by
the type and name of the constant (an identifier), the assignment operator and the
constant value. It takes the general form:
consttypevar=value;
3-6 Chapter 3
To distinguish between the different data types, programmers often use certain
conventions for naming variables and constants. They prefix each variable or constant
with 3 lowercase letters representing the data type. The table below shows the prefixes
for several data types.
Data Type
bool
byte
short
float
double
Prefix
bln
bte
shr
flt
dbl
Data Type
decimal
int
long
string
char
Prefix
dec
int
lng
str
chr
The following are some examples of variable and constant declarations using the above
convention:
stringstrProductCode;
intintQuantity;
constdoubledblRate=7.50;
Alias For
System.SByte
Allowed Values
-128 to 127
C# Basics 3-7
byte
short
ushort
int
uint
long
System.Byte
System.Int16
System.UInt16
System.Int32
System.UInt32
System.Int64
ulong
float
double
decimal
char
bool
string
System.UInt64
System.Float
System.Double
System.Decimal
System.Char
System.Boolean
System.String
0 to 255
-32,768 to 32,767
0 to 65,535
-2,147,483,648 to 2,147,483,647
0 to 4,294,967,295
-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
0 to 18,446,744,073,709,551,615
1.510-45 to 3.41038
5.010-324 to 1.710308
1.010-28 to 7.91028
0 to 65535
True or false
A sequence of characters
You must choose the appropriate data type for the variables you use. For example, you
can choose the short data type for small integer numbers (positive and negative),
int for bigger integer numbers, and long for very large integer numbers. If you only
need positive integers (for example, to store the population of a country), then you can
use the unsigned integer data type uint. For calculations involving financial
calculations, you can choose the decimal data type. Similarly, for single characters,
you would choose the char data type, and for a string of characters, you would
choose the string data type.
Arithmetic Operators
The arithmetic operators are as follows.
Operator
+
*
/
%
Action
Subtraction (also unary minus)
Addition
Multiplication
Division
Remainder (modulus)
3-8 Chapter 3
Shift bits right
Shift bits left
>>
<<
+
*
/
%
b
b
b
c
b
Value
5
11
24
1.5
2
Note that there are no implied multiplication operations in C#. That means, you cannot
write ab or (a)(b) to mean a times b. You have to write the multiplication
operation explicitly as a*b.
Relational Operators
There are six relational operators in C#:
Operator
==
<
>
<=
>=
!=
Meaning
Equal to
Less than
Greater than
Less than or equal to
Greater than or equal to
Not equal to
Note that some operators, e.g., <= and >= have two symbols. C# treats the two
symbols as a single operator.
The result of a relational operation is always true or false. For example, if
a = 3, b = 4 and c = 5, then the following holds:
a > b
a <= c
c >= 5
(a+b) == c
c < (a+b)
Boolean/Logical Operators
C# Basics 3-9
There are two main Boolean or logical operators in C# - && (AND) and || (OR).
These operators are used to perform logical operations.
Operator
Meaning
& or &&
Logical AND
| or ||
Logical OR
^
Logical XOR
!
Logical NOT
Note: Although you can use the operators | (&) and || (&&) interchangeably for the
logical OR and logical AND, there is however a subtle difference. When you use the
two character operators (|| and &&), it may not be necessary to evaluate all the
operands in an expression. For example, if x and y are Boolean, the expression
x & y will yield false if x is false. It is not necessary to evaluate y. This however
is not the case when you use the single character operator (| or &) where all the
operands are evaluated. Thus using || and && will result in slightly better
performance.
The table below summarizes the results of the various logical operations for the
Boolean variables xand y.
x
true
true
false
false
y
true
false
true
false
x || y
true
true
true
false
x && y
true
false
false
false
//sameasx | y
//sameasx & y
You can combine all the operators (arithmetic, relational and logical) in an expression
as in the following examples, given a = 2, b = 3, c = 4 and d = 5:
a < b || c < d
a > b && c > d
Other Operators
will yieldtrue
will yieldfalse
3-10 Chapter 3
C# has other operators such as the following:
Operator
is
?:
this
Meaning
Tests data/object type
Simple ifelse
Refers to current object
The is operator tests the data type of a variable. The ?: operator is a simple ifelse
conditional operator. The this operator references the current object.
Example
If i is of type int (integer) and x is of type double,
i is double will yield the value false
x is double will yield the value true
Example
If sex is of type char and status is of type string, the statement
status=(sex==M?Mr:Ms);
will assign the string Mr to status if sex is equal to M, otherwise it will assign Ms.
Example
If small, x and y are of type int, the statement
small=(x<=y?x:y)
Expressions
We have already looked at several examples of arithmetic expressions. An expression
can take the form of a constant, variable, computation or formula. It can include
blanks to make the code more readable.
We have already seen the order of operator precedence. They follow the usual algebraic
rules. For example, in an expression involving multiplication, division, addition and
subtraction, the multiplication and division operations will be performed first before
C# Basics 3-11
the addition and subtraction. When the operators have the same precedence (example
multiplication and division), the order of evaluation is always from left to right. You
can use a pair of parentheses () in an expression to force the order of evaluation
(expressions within parentheses will be evaluated first).
Here are some examples of expressions:
sum2 / n
(a * b c) / (d 2 * e)
((b + 2 4 * a * c)) / (2 * a)
50 % 12
// get the remainder of 50 divided by 12
Boolean/logical variables are executed in a similar way. The operator & has a higher
precedence than the operator |. Again, parentheses may be used to force the order of
evaluation.
The statement can be interpreted as follows: evaluate the expression on the right-hand
side of the operator (=) and assign the result to the variable on the left-hand side of the
operator. The expression on the right-hand side can be a constant, a variable or an
expression. The assignment operator is not the same as the equal sign used in
mathematics. Here are some examples of assignment statements.
age = 20;
more = true;
greetings = Hello there;
MyName = Maria;
amount = item_price * quantity;
pay = basic + allowance + hours_worked * rate;
net_pay = pay 0.12 * pay;
To show the effect of an assignment, we show below how the contents of the memory
before and after the assignment for the first four assignment statements above.
3-12 Chapter 3
Before
Variable
After
Contents of
memory
age
more
greetings
MyName
Variable
0
false
age
more
greetings
MyName
Contents of
memory
20
true
Hello there
Maria
There are also several variations of the assignment operator, e.g., *=, +=, and %=. If
these operators are used, the variable on the left-hand side also acts as the first operand
in the expression on the right-hand. For example, if x = 8 and y = 5, you will have
the following results.
Operator
*=
/=
+=
-=
%=
Example
Equivalent to
Result
x
x
x
x
x
x
x
x
x
x
*=
/=
+=
-=
%=
y
y
y
y
y
=
=
=
=
=
x
x
x
x
x
*
/
+
y
y
y
y
y
For example, if x is an integer variable and y is a double variable, then the statement
y = (double) x;
C# Basics 3-13
Similarly, if x and n are integer variables and y is a double variable, then the statement
y = (double) x / n;
would convert x to double first before dividing it by n and assigning the result to y.
The data type of the variable on the left-hand-side of the assignment operator must be
long enough to hold the value of the expression on the right-hand side.
The same also applies to objects in a superclass and subclass. For example, if s is an
object of type sub and ss is an object of type sup, and if sub is a subclass of sup,
then the statement
s = (sub) ss;
// box a number
// unbox a number
x is boxed
// unboxing a long
int
Why do you need two types of data structures 5 stack and heap? Ordinary variables
object
= stack because the compiler knows exactly how much memory is
are stored
on ythe
needed. x;
But instance variables are different; they are created dynamically at runtime.
3-14 Chapter 3
The memory requirements can change as instances are created and destroyed. C#
provides a memory manager called garbage collector to reclaim memory on the heap
when objects are deleted or go out of scope.
So it is important to trap and handle such errors. To do this, C# provides the keyword
checked and unchecked types. It takes the following form:
checked (expression)
unchecked (expression)
When you use checked, the system throws an exception as in Program 3.2.
Program 3.2
using System;
class checking
C# Basics 3-15
{
public static void Main()
{
int x = 2000000000;
int y = checked (x + x);
Console.WriteLine("Value of y = " + y);
}
}
When you run this program you will get an error message in a dialog box.
Unhandled Exception: System.OverflowException: Arithmetic
operation resulted in an overflow.
At checking.Main() in
c:\c# projects\windowsapplication2\consoleapplication12
\class1.cs:line 7
You can catch the above error by recoding the program as in Program 3.3.
Program 3.3
using System;
class checking
{
public static void Main()
{
int x = 2000000000;
try
{
int y = checked (x + x);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
You will get the same error message as above. But in this case, your program catches
the error.
3-16 Chapter 3
The unchecked simply reverses the effect of checked. Program 3.4 illustrates
unchecked.
Program 3.4
using System;
class checking
{
public static void Main()
{
int x = 2000000000;
int y = unchecked (x + x);
Console.WriteLine("Value of y = " + y);
}
}
The above code will produce the incorrect result Value of y = -294967296
Note that you can also apply checked/unchecked on a block as in Program 3.5.
This has the same effect as the code above.
Program 3.5
using System;
class checking
{
public static void Main()
{
int x = 2000000000;
unchecked
{
int y = x + x;
Console.WriteLine("Value of y = " + y);
}
}
}
C# Basics 3-17
Programs need input (i.e., data) from users and they generate output (information in
the form of reports) to users. The standard input device is the keyboard and the
standard output device is the monitor. That is, you enter input via the keyboard and
display out on the monitor. C# provides the Console class (which is part of the
System namespace) to perform input/output.
The common methods for reading data are Read() and ReadLine(). These
methods allow you to read text data from the keyboard. Read() is used for reading a
single character while ReadLine() is used for reading a string of characters
terminated by a carriage return (Enter key).
The common methods for displaying computer output are Write() and
WriteLine(). These methods allow you to display output on the screen. Write()
is used to display the specified output and position the cursor immediately after the
output while WriteLine() is used to display the specified output and move the
cursor position to the beginning of the next line.
Program 3.6 illustrates the input/output statements.
Program 3.6
using System;
class InputOutput
{
public static void Main()
{
string name;
int age;
Console.Write("Enter name: ");
name = Console.ReadLine();
// display message
// read and store name
3-18 Chapter 3
Enter name: Jane
Enter age: 25
Name:Jane
Age :25
Note that in the above program age is entered as text and is converted to an integer by
the converter method ToInt32() which is part of the Convert class. This class
has other converter methods to convert text data to long, double, float, etc.
The + in the statement
Console.WriteLine("Age :" + age);
is a concatenation operator. It displays the message and then prints the value of age
after the colon.
You can use a pair of curly braces {} to specify output items as in the following
statement
Console.WriteLine("Age :{0}", age);
The above statement displays the same result. When brackets are used, they are
numbered {0}, {1}, etc.
For example, in the above program, you can replace the two statements
Console.WriteLine("\nName:" + name);
Console.WriteLine("Age :" + age);
C# Basics 3-19
MessageBox and the method Show(). Program 3.7 illustrates the use of a message
box.
Program 3.7
using System;
using System.Windows.Forms;
namespace nsMessageBox
{
class clsOutput
{
public static void Main()
{
string name;
int age;
Console.Write("Enter name: ");
name = Console.ReadLine();
Console.Write("Enter age: ");
age = Convert.ToInt32(Console.ReadLine());
MessageBox.Show("Name: " + name + "
Age: " + age);
}
}
}
When you run the program, the output will appear in a message box as shown below.
A message box can display only simple output. One output statement will show one
message box and two output statements will show two message boxes one by one. You
cannot use escape sequences (e.g., \n, \t) or braces ({0}, {1}) to display output
in a message box.
To use message box in a Console Application, you need to compile and run under the
Visual Studio 2005 Command Prompt.
The steps are as follows:
1. Edit the program as a Console Application.
3-20 Chapter 3
>
Visual
Studio
4. Change to c drive, then compile and run as shown in the screen below.
3.10 Namespaces
A namespace is a collection of related classes. It provides unique identifiers for types
by placing them in a hierarchical structure. It also provides help in avoiding name
clashes between two sets of code. The classes of the System namespace are given
below.
The fundamental programming namespaces in the .NET Framework include:
Namespace
Classes Contained
System
C# Basics 3-21
derived, is defined in System, as are the primitive data
types int, string, double etc.
System.Reflection
System.IO
System.Collections
System.Web
System.Net
System.Data
System.WinForms
Microsoft.Win32
Program 3.8 shows how to create a namespace. To declare a new namespace csharp,
Directory
ArrayList
you put the reserved word namespace
in front of csharp.
Curly braces surround
Configuration
the members
inside the csharp namespace.
IOException
BitArray
File
SortedList
FileStream
Stack
Diagnostics
Program 3.8
Globalization
using System;
namespace csharp //Namespace declaration
Queue
StreamReader
Net
{
class NameSpaceCSS
StreamWriter
ICollection
{
IO
public static void Main()
{
IList
StringReader
//Write to console
Reflection
Console.WriteLine("csharp namespace");
IComparer
StringWriter
}
}
Resources
Decoder
Runtime
Security
Text
Encoder
Encoding
StringBuilder
ASCIIEncoding
Threading
Thread
ThreadPool
Timer
Timeout
ThreadStart
ThreadState
ThreadExceptionEventHandler
3-22 Chapter 3
}
Example
Program 3.9 shows how to create a nested namespace. By placing the code in different
sub namespaces, we can keep our code organized.
Program 3.9
using System;
namespace csharp //Namespace declaration
{
namespace csharp2 //Namespace declaration
{
class NameSpaceCSS //Program start class
{
public static void Main()
{
//Write to console
Console.WriteLine("nested namespaces");
}
}
}
}
Exercise
3.1 List the main data types provided in C#.
3.2 Write appropriate declarations, assigning initial values (if any), for each of the
following:
(a) Integer variable: index
Unsigned integer variable: cust_num
Double-precision variables: gross, tax, net
C# Basics 3-23
3.5. Using the values given in question 3.4, determine the values for the each of the
expressions given below:
(a) a++
(b) a<2 && y>5.0
(c) c>=a
(d) a<b || b>c
(e) z!=10.0
3-24 Chapter 3
(f) a==25
3.7 Explore the classes in the System namespace and determine their purpose.
3.8 What is the purpose of boxing and unboxing a variable/object? Illustrate with a
simple example.
3.9 What is the purpose of checked and unchecked? Illustrate with a simple example.
3.10 Why do you need two types of data structures (stack and heap) for storing
variables and references to instance variables?
3.11 What is the purpose of garbage collector? What will happen if there is no
garbage collector?