Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: C# notes
Description: notes

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


1

About the Tutorial
C# is a simple, modern, general-purpose, object-oriented programming language
developed by Microsoft within its
...
This tutorial
covers basic C# programming and various advanced concepts related to C#
programming language
...


Prerequisites
C# programming is very much based on C and C++ programming languages, so if
you have a basic understanding of C or C++ programming, then it will be fun to learn
C#
...
Ltd
...
Ltd
...
We strive to update the contents of our
website and tutorials as timely and as precisely as possible, however, the contents
may contain inaccuracies or errors
...
Ltd
...
If you discover any errors on our website or in this tutorial,
please notify us at contact@tutorialspoint
...


i

Contents
About the Tutorial
...
i
Prerequisites
...
i
Contents
...


OVERVIEW
...
1

2
...
3
The
...
3
Integrated Development Environment (IDE) for C#
...
4

3
...
5
Creating Hello World Program
...
6
C# Keywords
...


BASIC SYNTAX
...
13
The class Keyword
...
14
Member Variables
...
14
Instantiating a Class
...
15
C# Keywords
...


DATA TYPES
...
17
Reference Type
...
19
Dynamic Type
...
19
Pointer Type
...


TYPE CONVERSION
...
22

7
...
24
Defining Variables
...
25
Accepting Values from User
...
26

8
...
28
Integer Literals
...
29
Character Constants
...
30
Defining Constants
...


OPERATORS
...
33
Relational Operators
...
38
Bitwise Operators
...
43
Miscillaneous Operators
...
48

10
...
51
if Statement
...
else Statement
...
else if
...
56
Nested if Statements
...
60
The ? : Operator
...


LOOPS
...
67
For Loop
...
While Loop
...
75
Loop Control Statements
...
83

12
...
84
Public Access Specifier
...
86
Protected Access Specifier
...
88

13
...
91
Defining Methods in C#
...
92
Recursive Method Call
...
96
Passing Parameters by Value
...
99
Passing Parameters by Output
...


NULLABLES
...
105

15
...
107
Declaring Arrays
...
107
Assigning Values to an Array
...
108
Using the foreach Loop
...
111
Multidimensional Arrays
...
112
Jagged Arrays
...
117
Param Arrays
...
119
Properties of the Array Class
...
120

16
...
124
Creating a String Object
...
126
Methods of the String Class
...


STRUCTURES
...
135
Features of C# Structures
...
138

18
...
141
Declaring enum Variable
...


CLASSES
...
143
Member Functions and Encapsulation
...
148
C# Destructors
...
152

20
...
156
Base and Derived Classes
...
158
Multiple Inheritance in C#
...


POLYMORPHISM
...
163
Dynamic Polymorphism
...


OPERATOR OVERLOADING
...
170
Overloadable and Non-Overloadable Operators
...


INTERFACES
...
181

24
...
184
Defining a Namespace
...
185
Nested Namespaces
...


PREPROCESSOR DIRECTIVES
...
190
The #define Preprocessor
...
192

26
...
194
Constructs for Defining Regular Expressions
...
194
Character Classes
...
198
Quantifier
...
200
Alternation Constructs
...
202
Miscellaneous Constructs
...
203

27
...
208
Exception Classes in C#
...
210
Creating User-Defined Exceptions
...
213

28
...
214
C# I/O Classes
...
215
Advanced File Operations in C#
...
218
The StreamReader Class
...
220

vii

Reading from and Writing into Binary files
...
224
Windows File System
...
228
The FileInfo Class
...


ATTRIBUTES
...
234
Predefined Attributes
...
234
Conditional
...
237
Creating Custom Attributes
...
239
Applying the Custom Attribute
...


REFLECTION
...
243
Viewing Metadata
...


PROPERTIES
...
251
Abstract Properties
...


INDEXERS
...
259
Overloaded Indexers
...


DELEGATES
...
266
Instantiating Delegates
...
268
Using Delegates
...


EVENTS
...
272
Declaring Events
...


COLLECTIONS
...
280
Hashtable Class
...
288
Stack Class
...
295
BitArray Class
...


GENERICS
...
304
Generic Methods
...
306

37
...
309
Writing an Anonymous Method
...


UNSAFE CODES
...
312
Retrieving the Data Value Using a Pointer
...
314
Accessing Array Elements Using a Pointer
...
316

39
...
318
Thread Life Cycle
...
319
Creating Threads
...
324
Destroying Threads
...
OVERVIEW
C# is a modern, general-purpose, object-oriented programming language developed
by Microsoft and approved by European Computer Manufacturers Association (ECMA)
and International Standards Organization (ISO)
...
Net
Framework
...

The following reasons make C# a widely used professional language:


It is a modern, general-purpose programming language



It is object oriented
...




It is easy to learn
...




It produces efficient programs
...




It is a part of
...


Strong Programming Features of C#
Although C# constructs closely follow traditional high-level languages, C and C++
and being an object-oriented programming language
...

Following is the list of few important features of C#:


Boolean Conditions



Automatic Garbage Collection



Standard Library



Assembly Versioning



Properties and Events



Delegates and Events Management



Easy-to-use Generics



Indexers

1



Conditional Compilation



Simple Multithreading



LINQ and Lambda Expressions



Integration with Windows

2

2
...
We
have already mentioned that C# is part of
...
Net applications
...
Net framework
...
Net Framework
The
...
Net framework applications are multi-platform applications
...
All these languages can access the
framework as well as communicate with each other
...
Net framework consists of an enormous library of codes used by the client
languages such as C#
...
Net framework:


Common Language Runtime (CLR)



The
...
Net and ASP
...
Net



Windows Workflow Foundation (WF)



Windows Presentation Foundation



Windows Communication Foundation (WCF)



LINQ

For the jobs each of these components perform, please see ASP
...


3

Integrated Development Environment (IDE) for C#
Microsoft provides the following development tools for C# programming:


Visual Studio 2010 (VS)



Visual C# 2010 Express (VCE)



Visual Web Developer

The last two are freely available from Microsoft official website
...
You can also write C# source code files using a basic text
editor like Notepad, and compile the code into assemblies using the command-line
compiler, which is again a part of the
...

Visual C# Express and Visual Web Developer Express edition are trimmed down
versions of Visual Studio and has the same appearance
...
In this tutorial, we have used Visual C# 2010 Express
...
It gets installed automatically on your
machine
...


Writing C# Programs on Linux or Mac OS
Although the
...
Mono is an open-source
version of the
...
Kindly check Go
Mono
...
NET applications
cross-platform, but also to bring better development tools for Linux developers
...


4

3
...


Creating Hello World Program
A C# program consists of the following parts:


Namespace declaration



A class



Class methods



Class attributes



A Main method



Statements and Expressions



Comments

Let us look at a simple code that prints the words "Hello World":
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
/* my first program in C# */
Console
...
ReadKey();
}
}
}

5

When this code is compiled and executed, it produces the following result:
Hello World
Let us look at the various parts of the given program:


The first line of the program using System; - the using keyword is used to
include the System namespace in the program
...




The next line has the namespace declaration
...
The HelloWorldApplication namespace contains the class HelloWorld
...
Classes generally contain
multiple methods
...
However, the
HelloWorld class has only one method Main
...
The Main method states what the class does when executed
...
*/ is ignored by the compiler and it is put to add
comments in the program
...
WriteLine("Hello World");



WriteLine is a method of the Console class defined in the System namespace
...




The last line Console
...
NET Users
...
NET
...




All statements and expression must end with a semicolon (;)
...




Unlike Java, program file name could be different from the class name
...
Net for compiling and executing C# programs, take the
following steps:


Start Visual Studio
...




Choose Visual C# from templates, and then choose Windows
...


6



Specify a name for your project and click OK button
...




Write code in the Code Editor
...
A Command
Prompt window appears that contains the line Hello World
...




Save the file as helloworld
...




Type csc helloworld
...




If there are no errors in your code, the command prompt takes you to the next
line and generates helloworld
...




Type helloworld to execute your program
...


C# is an object-oriented programming language
...
The actions that an object may take are called methods
...

For example, let us consider a Rectangle object
...
Depending upon the design, it may need ways for accepting the values of
these attributes, calculating the area, and displaying details
...
5;

7

width = 3
...
WriteLine("Length: {0}", length);
Console
...
WriteLine("Area: {0}", GetArea());
}
}

class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r
...
Display();
Console
...
5

8

Width: 3
...
75

The using Keyword
The first statement in any C# program is
using System;

The using keyword is used for including the namespaces in the program
...


The class Keyword
The class keyword is used for declaring a class
...
Compilers ignore the comment entries
...
For example,
}//end class Rectangle

Member Variables
Variables are attributes or data members of a class, used for storing data
...


Member Functions
Functions are set of statements that perform a specific task
...
Our sample class Rectangle contains three
member functions: AcceptDetails, GetArea and Display
...


Identifiers
9

An identifier is a name used to identify a class, variable, function, or any other userdefined item
...
The first character in an identifier cannot be a
digit
...
; : " ' / and \
...




It should not be a C# keyword
...
These keywords cannot
be used as identifiers
...

In C#, some identifiers have special meaning in context of code, such as get and set
are called contextual keywords
...
BASIC SYNTAX
C# is an object-oriented programming language
...
The actions that an object may take are called methods
...

For example, let us consider an object Rectangle
...
Depending upon the design, it may need ways for accepting the values of
these attributes, calculating area, and display details
...
5;
width = 3
...
WriteLine("Length: {0}", length);
Console
...
WriteLine("Area: {0}", GetArea());
}
}

class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r
...
Display();
Console
...
5
Width: 3
...
75

The using Keyword
The first statement in any C# program is using System;

13

The using keyword is used for including the namespaces in the program
...


The class Keyword
The class keyword is used for declaring a class
...
Compiler ignores the comment entries
...
For example,
}//end class Rectangle

Member Variables
Variables are attributes or data members of a class
...

In the preceding program, the Rectangle class has two member variables
named length and width
...
The member functions
of a class are declared within the class
...


Instantiating a Class
In the preceding program, the class ExecuteRectangle is used as a class, which
contains the Main() method and instantiates the Rectangle class
...
The basic rules for naming classes in C# are as follows:


A name must begin with a letter that could be followed by a sequence of letters,
digits (0 - 9), or underscore
...




It must not contain any embedded space or symbol like ? - +! @ # % ^ & * (
) [ ] { }
...
However, an underscore ( _ ) can be used
...


C# Keywords
Keywords are reserved words predefined to the C# compiler
...
However, if you want to use these keywords as identifiers, you
may prefix them with the @ character
...

The following table lists the reserved keywords and contextual keywords in C#:
Reserved Keywords
abstract

as

base

bool

break

byte

case

catch

char

checked

class

const

continue

decimal

default

delegate

do

double

else

enum

event

explicit

extern

false

finally

fixed

float

for

foreach

goto

if

implicit

in

in (generic
int
modifier)

interface

internal

is

lock

long

namespace new

params

sbyte

null

object

operator

out

out
(generic override
modifier)

private

protected

public

readonly

ref

return

15

sealed

short

sizeof

stackalloc

static

string

struct

switch

this

throw

true

try

typeof

uint

ulong

unchecked

unsafe

ushort

using

virtual

void

volatile

while

Contextual Keywords
add

alias

ascending

descending dynamic

from

get

global

group

into

join

orderby

partial
(type)

partial
(method)

remove

select

set

let

16

5
...
They are derived from the class
System
...

The value types directly contain data
...
When you
declare an int type, the system allocates memory to store the value
...
9 x 1028 to 7
...
0M

double

64-bit
double-precision
(+/-)5
...
7 x 10308 0
...
4 x 1038 to + 3
...
0F

Int

32-bit signed integer type -2,147,483,648 to 2,147,483,647

0

long

64-bit signed integer type

-923,372,036,854,775,808
9,223,372,036,854,775,807

sbyte

8-bit signed integer type

-128 to 127

to

0L
0

17

short

16-bit signed integer type -32,768 to 32,767

0

uint

32-bit unsigned integer
0 to 4,294,967,295
type

0

ulong

64-bit unsigned integer
0 to 18,446,744,073,709,551,615
type

0

ushort

16-bit unsigned integer
0 to 65,535
type

0

To get the exact size of a type or a variable on a particular platform, you can use
the sizeof method
...
Following is an example to get the size of int type on any machine:
namespace DataTypeApplication
{
class Program
{
static void Main(string[] args)
{
Console
...
ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following result:
Size of int: 4

Reference Type
The reference types do not contain the actual data stored in a variable, but they
contain a reference to the variables
...
Using multiple variables, the
reference types can refer to a memory location
...

Example
are: object, dynamic, and string
...
Object is an alias for System
...
The object types can be
assigned values of any other types, value types, reference types, predefined or userdefined types
...

When a value type is converted to object type, it is called boxing and on the other
hand, when an object type is converted to a value type, it is called unboxing
...
Type checking for
these types of variables takes place at run-time
...


String Type
The String Type allows you to assign any string values to a variable
...
String class
...
The value for a
string type can be assigned using string literals in two forms: quoted and @quoted
...
We will discuss
these types in later chapter
...
Pointers in C# have
the same capabilities as the pointers in C or C++
...


20

6
...
It is also known as
Type Casting
...
For example, conversions from smaller to larger integral types
and conversions from derived classes to base classes
...
Explicit conversions require a cast operator
...
74;
int i;

// cast double to int
...
WriteLine(i);
Console
...
No
...


2

ToByte
Converts a type to a byte
...

ToDateTime
Converts a type (integer or string type) to date-time structures
...


6

ToDouble
Converts a type to a double type
...


8

ToInt32
Converts a type to a 32-bit integer
...


10

ToSbyte
Converts a type to a signed byte type
...


12

ToString
Converts a type to a string
...


14

ToUInt16
Converts a type to an unsigned int type
...


16

ToUInt64
Converts a type to an unsigned big integer
...
005f;
double d = 2345
...
WriteLine(i
...
WriteLine(f
...
WriteLine(d
...
WriteLine(b
...
ReadKey();

}
}
}
When the above code is compiled and executed, it produces the following result:
75
53
...
7652
True

23

7
...
Each variable in C# has a specific type, which determines the size and
layout of the variable's memory, the range of values that can be stored within that
memory, and the set of operations that can be applied to the variable
...


Defining Variables
Syntax for variable definition in C# is:
;

Here, data_type must be a valid C# data type including char, int, float, double, or
any user-defined data type, and variable_list may consist of one or more identifier
names separated by commas
...
The general form of initialization is:
variable_name = value;

Variables can be initialized in their declaration
...
*/

byte z = 22;

/* initializes z
...
14159; /* declares an approximation of pi
...
*/

It is a good programming practice to initialize variables properly, otherwise
sometimes program may produce unexpected result
...
WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console
...

For example,
int num;
num = Convert
...
ReadLine());

The function Convert
...
ReadLine() accepts the data in string format
...
lvalue: An expression that is an lvalue may appear as either the left-hand or

right-hand side of an assignment
...
rvalue: An expression that is an rvalue may appear on the right- but not left-

hand side of an assignment
...
Numeric literals are rvalues and hence they may not be assigned and
can not appear on the left-hand side
...
CONSTANTS AND LITERALS
The constants refer to fixed values that the program may not alter during its
execution
...
Constants can be of any of the
basic data types like an integer constant, a floating constant, a character constant,
or a string literal
...

The constants are treated just like regular variables except that their values cannot
be modified after their definition
...
A prefix specifies
the base or radix: 0x or 0X for hexadecimal, 0 for octal, and no prefix id for decimal
...
The suffix can be uppercase or lowercase and can be in any
order
...
You can represent floating point literals either in decimal form or
exponential form
...
14159

/* Legal */

314159E-5L

/* Legal */

510E

/* Illegal: incomplete exponent */

210f

/* Illegal: no decimal or exponent */


...
The signed exponent is introduced by e
or E
...
For example, 'x' and can be stored
in a simple variable of char type
...

There are certain characters in C# when they are preceded by a backslash
...

Here, is a list of some of such escape sequence codes:
Escape sequence

Meaning

\\

\ character

\'

' character

\"

" character

\?

? character

\a

Alert or bell

\b

Backspace

\f

Form feed

\n

Newline

\r

Carriage return

\t

Horizontal tab

29

\v

Vertical tab

\ooo

Octal number of one to three digits

\xhh
...
WriteLine("Hello\tWorld\n\n");
Console
...
A string
contains characters that are similar to character literals: plain characters, escape
sequences, and universal characters
...

Here are some examples of string literals
...

"hello, dear"
"hello, \

30

dear"
"hello, " "d" "ear"
@"hello dear"

Defining Constants
Constants are defined using the const keyword
...
14159; // constant declaration
double r;
Console
...
ToDouble(Console
...
WriteLine("Radius: {0}, Area: {1}", r, areaCircle);
Console
...
27431

32

9
...
C# has rich set of built-in operators and provides the following
type of operators:


Arithmetic Operators



Relational Operators



Logical Operators



Bitwise Operators



Assignment Operators



Misc Operators

This tutorial explains the arithmetic, relational, logical, bitwise, assignment, and
other operators one by one
...
Assume
variable A holds 10 and variable B holds 20 then:
Operator

Description

Example

+

Adds two operands

A + B = 30

-

Subtracts second operand from the first

A - B = -10

*

Multiplies both operands

A * B = 200

/

Divides numerator by de-numerator

B/A=2

%

Modulus Operator and remainder of after an integer
division

B%A=0

++

Increment operator increases integer value by one

A++ = 11

--

Decrement operator decreases integer value by one

A-- = 9

Example
33

The following example demonstrates all the arithmetic operators available in C#:
using System;

namespace OperatorsAppl
{
class Program
{
static void Main(string[] args)
{
int a = 21;
int b = 10;
int c;

c = a + b;
Console
...
WriteLine("Line 2 - Value of c is {0}", c);
c = a * b;
Console
...
WriteLine("Line 4 - Value of c is {0}", c);
c = a % b;
Console
...
WriteLine("Line 6 - Value of c is {0}", c);
c = a--;
Console
...
ReadLine();

34

}
}
}
When the above code is compiled and executed, it produces the following result:
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22

Relational Operators
Following table shows all the relational operators supported by C#
...


(A == B) is not
true
...


(A != B) is true
...


(A > B) is not
true
...


(A < B) is true
...


(A >= B) is not
true
...


(A <= B) is true
...
WriteLine("Line 1 - a is equal to b");
}
else
{
Console
...
WriteLine("Line 2 - a is less than b");
}

36

else
{
Console
...
WriteLine("Line 3 - a is greater than b");
}
else
{
Console
...
WriteLine("Line 4 - a is either less than or equal to

b");

}
if (b >= a)
{
Console
...
Assume
variable A holds Boolean value true and variable B holds Boolean value false, then:

Operator

Description

Example

&&

Called Logical AND operator
...


(A && B) is false
...
If any of the two
operands is non zero then condition becomes true
...


!

Called Logical NOT Operator
...
If a condition is true
then Logical NOT operator will make false
...


Example
The following example demonstrates all the logical operators available in C#:
using System;

namespace OperatorsAppl
{
class Program
{
static void Main(string[] args)
{
bool a = true;
bool b = true;

38

if (a && b)
{
Console
...
WriteLine("Line 2 - Condition is true");
}
/* lets change the value of

a and b */

a = false;
b = true;
if (a && b)
{
Console
...
WriteLine("Line 3 - Condition is not true");
}
if (!(a && b))
{
Console
...
ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following result:
39

Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true

Bitwise Operators
Bitwise operator works on bits and perform bit by bit operation
...
Assume
variable A holds 60 and variable B holds 13, then:

Operator

Description

Example

40

&

Binary AND Operator copies a bit to the result if it
exists in both operands
...

is 0011 1101

^

Binary XOR Operator copies the bit if it is set in one
operand but not both
...


(~A ) = 61, which
is 1100 0011 in
2's
complement
due to a signed
binary number
...
The left operands value is
moved left by the number of bits specified by the
right operand
...
The left operands value
is moved right by the number of bits specified by the
right operand
...
WriteLine("Line 1 - Value of c is {0}", c );

c = a | b;

/* 61 = 0011 1101 */

Console
...
WriteLine("Line 3 - Value of c is {0}", c);

c = ~a;

/*-61 = 1100 0011 */

Console
...
WriteLine("Line 5 - Value of c is {0}", c);

c = a >> 2;

/* 15 = 0000 1111 */

Console
...
ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following result:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240

42

Line 6 - Value of c is 15

Assignment Operators
There are following assignment operators supported by C#:
Operator

Description

Example

=

Simple assignment operator, Assigns values from right
side operands to left side operand

C = A + B
assigns value of
A + B into C

+=

Add AND assignment operator, It adds right operand
to the left operand and assign the result to left
operand

C += A is
equivalent to C
=C+A

-=

Subtract AND assignment operator, It subtracts right
operand from the left operand and assign the result to
left operand

C -= A is
equivalent to C
=C–A

*=

Multiply AND assignment operator, It multiplies right
operand with the left operand and assign the result to
left operand

C *= A is
equivalent to C
=C*A

/=

Divide AND assignment operator, It divides left
operand with the right operand and assign the result
to left operand

C /= A is
equivalent to C
=C/A

%=

Modulus AND assignment operator, It takes modulus
using two operands and assign the result to left
operand

C %= A is
equivalent to C
=C%A

<<=

Left shift AND assignment operator

C <<= 2 is
same as C = C
<< 2

>>=

Right shift AND assignment operator

C >>= 2 is
same as C = C
>> 2

&=

Bitwise AND assignment operator

C &= 2 is same
as C = C & 2

43

^=

bitwise exclusive OR and assignment operator

C ^= 2 is same
as C = C ^ 2

|=

bitwise inclusive OR and assignment operator

C |= 2 is same
as C = C | 2

Example
The following example demonstrates all the assignment operators available in C#:
using System;

namespace OperatorsAppl
{
class Program
{
static void Main(string[] args)
{
int a = 21;
int c;

c = a;
Console
...
WriteLine("Line 2 - += Value of c = {0}", c);

c -= a;
Console
...
WriteLine("Line 4 - *=

Value of c = {0}", c);

44

c /= a;
Console
...
WriteLine("Line 6 - %=

Value of c = {0}", c);

c <<= 2;
Console
...
WriteLine("Line 8 - >>=

Value of c = {0}", c);

c &= 2;
Console
...
WriteLine("Line 10 - ^=

Value of c = {0}", c);

c |= 2;
Console
...
ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following result:
Line 1 - =

Value of c = 21

45

Line 2 - +=

Value of c = 42

Line 3 - -=

Value of c = 21

Line 4 - *=

Value of c = 441

Line 5 - /=

Value of c = 21

Line 6 - %=

Value of c = 11

Line 7 - <<=

Value of c = 44

Line 8 - >>=

Value of c = 11

Line 9 - &=

Value of c = 2

Line 10 - ^=

Value of c = 0

Line 11 - |=

Value of c = 2

Miscillaneous Operators
There are few other important operators including sizeof, typeof and ? : supported
by C#
...


sizeof(int), returns 4
...


typeof(StreamReader);

&

Returns the address of an variable
...


*

Pointer to a variable
...


?:

Conditional Expression

If Condition is true ? Then
value X : Otherwise value Y

is

Determines whether an object is of a
certain type
...


46

as

Cast without raising an exception if the
cast fails
...
WriteLine("The size of int is {0}", sizeof(int));
Console
...
WriteLine("The size of double is {0}", sizeof(double));

/* example of ternary operator */
int a, b;
a = 10;
b = (a == 1) ? 20 : 30;
Console
...
WriteLine("Value of b is {0}", b);

47

Console
...
This affects
evaluation of an expression
...

For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has
higher precedence than +, so the first evaluation takes place for 3*2 and then 7 is
added into it
...
Within an expression, higher precedence
operators are evaluated first
...
++ - -

Left to right

Unary

+ - ! ~ ++ - - (type)* & sizeof

Right to left

Multiplicative

*/%

Left to right

Additive

+-

Left to right

48

Shift

<< >>

Left to right

Relational

< <= > >=

Left to right

Equality

== !=

Left to right

Bitwise AND

&

Left to right

Bitwise XOR

^

Left to right

Bitwise OR

|

Left to right

Logical AND

&&

Left to right

Logical OR

||

Left to right

Conditional

?:

Right to left

Assignment

= += -= *= /= %=>>= <<= &= ^= |=

Right to left

Comma

,

Left to right

Example
using System;

namespace OperatorsAppl
{

class Program
{
static void Main(string[] args)
{
int a = 20;

49

int b = 10;
int c = 15;
int d = 5;
int e;
e = (a + b) * c / d;

// ( 30 * 15 ) / 5

Console
...
WriteLine("Value of ((a + b) * c) / d is

e = (a + b) * (c / d);

: {0}", e);

// (30) * (15/5)

Console
...
WriteLine("Value of a + (b * c) / d is

: {0}", e);

Console
...
DECISION MAKING
Decision making structures requires the programmer to specify one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and optionally,
other statements to be executed if the condition is determined to be false
...
Click the following links
to check their detail
...


if
...


nested
statements

You can use one if or else if statement inside another if or else
if statement(s)
...


nested
switch
statements

You can use one switch statement inside another switch
statement(s)
...


Syntax
The syntax of an if statement in C# is:
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}

If the boolean expression evaluates to true, then the block of code inside the if
statement is executed
...


Flow Diagram

52

Example
using System;
namespace DecisionMaking
{

class Program
{
static void Main(string[] args)
{
/* local variable definition */
int a = 10;

/* check the boolean condition using if statement */
if (a < 20)
{
/* if condition is true then print the following */
Console
...
WriteLine("value of a is : {0}", a);
Console
...
else Statement
An if statement can be followed by an optional else statement, which executes when
the boolean expression is false
...
else statement in C# is:
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}

If the boolean expression evaluates to true, then the if block of code is executed,
otherwise else block of code is executed
...
WriteLine("a is less than 20");
}
else
{
/* if condition is false then print the following */
Console
...
WriteLine("value of a is : {0}", a);
Console
...
else if
...
else statement, which is very
useful to test various conditions using single if
...

When using if, else if and else statements there are few points to keep in mind
...




An if can have zero to many else if's and they must come before the else
...


Syntax
The syntax of an if
...
else statement in C# is:
if(boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3)
{
/* Executes when the boolean expression 3 is true */
}
else
{
/* executes when the none of the above condition is true */
}

56

Example
using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{

/* local variable definition */
int a = 100;

/* check the boolean condition */
if (a == 10)
{
/* if condition is true then print the following */
Console
...
WriteLine("Value of a is 20");
}
else if (a == 30)
{
/* if else if condition is true

*/

Console
...
WriteLine("None of the values is matching");
}
Console
...
ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following result:
None of the values is matching
Exact value of a is: 100

Nested if Statements
It is always legal in C# to nest if-else statements, which means you can use one if
or else if statement inside another if or else if statement(s)
...
else in the similar way as you have nested if statement
...
WriteLine("Value of a is 100 and b is 200");
}
}
Console
...
WriteLine("Exact value of b is : {0}", b);
Console
...

Each value is called a case, and the variable being switched on is checked for
each switch case
...




You can have any number of case statements within a switch
...




The constant-expression for a case must be the same data type as the
variable in the switch, and it must be a constant or a literal
...




When a break statement is reached, the switch terminates, and the flow of
control jumps to the next line following the switch statement
...
If no break appears, the flow of
control will fall through to subsequent cases until a break is reached
...
The default case can be used for performing a task when
none of the cases is true
...


Flow Diagram

Example
using System;
namespace DecisionMaking
{

class Program
{
static void Main(string[] args)

61

{
/* local variable definition */
char grade = 'B';

switch (grade)
{
case 'A':
Console
...
WriteLine("Well done");
break;
case 'D':
Console
...
WriteLine("Better try again");
break;
default:
Console
...
WriteLine("Your grade is

{0}", grade);

Console
...

Even if the case constants of the inner and outer switch contain common values, no
conflicts will arise
...
WriteLine("This is part of outer switch ");
switch (b)
{
case 200:
Console
...
WriteLine("Exact value of a is : {0}", a);
Console
...
ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following result:
This is part of outer switch
This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200

64

The ? : Operator
We have covered conditional operator ? : in previous chapter which can be used to
replace if
...
It has the following general form:
Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2, and Exp3 are expressions
...

The value of a ? expression is determined as follows: Exp1 is evaluated
...
If Exp1 is
false, then Exp3 is evaluated and its value becomes the value of the expression
...
LOOPS
There may be a situation, when you need to execute a block of code several number
of times
...

Programming languages provide various control structures that allow for more
complicated execution paths
...
Click the
following links to check their detail
...
It tests the condition before executing the loop
body
...


66

do
...
while loop
...


Syntax
The syntax of a while loop in C# is:
while(condition)
{
statement(s);
}

Here, statement(s) may be a single statement or a block of statements
...
The loop
iterates while the condition is true
...


67

Flow Diagram

Here, key point of the while loop is that the loop might not ever run
...


Example
using System;

namespace Loops
{

class Program
{
static void Main(string[] args)
{
/* local variable definition */
int a = 10;

68

/* while loop execution */
while (a < 20)
{
Console
...
ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

For Loop
A for loop is a repetition control structure that allows you to efficiently write a loop
that needs to execute a specific number of times
...
The init step is executed first, and only once
...
You are not required to put a
statement here, as long as a semicolon appears
...
Next, the condition is evaluated
...


If it is false, the body of the loop does not execute and flow of control jumps
to the next statement just after the for loop
...
After the body of the for loop executes, the flow of control jumps back up to

the increment statement
...
This statement can be left blank, as long as a semicolon
appears after the condition
...
The condition is now evaluated again
...
After the condition becomes false, the for loop
terminates
...
WriteLine("value of a: {0}", a);
}
Console
...
While Loop
Unlike for and while loops, which test the loop condition at the start of the loop, the
do
...

A do
...
while loop is guaranteed
to execute at least one time
...
while loop in C# is:

72

do
{
statement(s);

}while( condition );

Notice that the conditional expression appears at the end of the loop, so the
statement(s) in the loop execute once before the condition is tested
...
This process repeats until the given condition becomes
false
...
WriteLine("value of a: {0}", a);
a = a + 1;
} while (a < 20);

Console
...
Following section shows few examples
to illustrate the concept
...
while loop statement in C# is as follows:
do
{
statement(s);
do
{

75

statement(s);
}while( condition );

}while( condition );

A final note on loop nesting is that you can put any type of loop inside of any other
type of loop
...


Example
The following program uses a nested for loop to find the prime numbers from 2 to
100:
using System;

namespace Loops
{

class Program
{
static void Main(string[] args)
{
/* local variable definition */
int i, j;

for (i = 2; i < 100; i++)
{
for (j = 2; j <= (i / j); j++)
if ((i % j) == 0) break; // if factor found, not prime
if (j > (i / j))
Console
...
ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following result:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime

77

89 is prime

97 is prime

Loop Control Statements
Loop control statements change execution from its normal sequence
...

C# provides the following control statements
...

Control Statement

Description

break statement

Terminates the loop or switch statement and transfers
execution to the statement immediately following the loop or
switch
...


Break Statement
The break statement in C# has following two usage:
1
...

2
...


If you are using nested loops (i
...
, one loop inside another loop), the break statement
will stop the execution of the innermost loop and start executing the next line of code
after the block
...
WriteLine("value of a: {0}", a);
a++;
if (a > 15)
{
/* terminate the loop using break statement */
break;
}
}
Console
...
Instead of
forcing termination, however, continue forces the next iteration of the loop to take
place, skipping any code in between
...

For
the while and do
...


Syntax
80

The syntax for a continue statement in C# is as follows:
continue;

Flow Diagram

Example
using System;

namespace Loops
{

class Program
{
static void Main(string[] args)
{
/* local variable definition */
int a = 10;

/* do loop execution */

81

do
{
if (a == 15)
{
/* skip the iteration */
a = a + 1;
continue;
}
Console
...
ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

82

Infinite Loop
A loop becomes infinite loop if a condition never becomes false
...
Since none of the three expressions that form the
for loop are required, you can make an endless loop by leaving the conditional
expression empty
...
WriteLine("Hey! I am Trapped");
}

}
}
}

When the conditional expression is absent, it is assumed to be true
...


83

12
...
Encapsulation, in object oriented programming
methodology, prevents access to implementation details
...

Abstraction allows making relevant information visible and encapsulation enables a
programmer to implement the desired level of abstraction
...
An access
specifier defines the scope and visibility of a class member
...
Any public member can be accessed from
outside the class
...
WriteLine("Length: {0}", length);
Console
...
WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r
...
5;
r
...
5;
r
...
ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Length: 4
...
5
Area: 15
...

The member function Display() and GetArea() can also access these variables directly
without using any instance of the class
...


Private Access Specifier
Private access specifier allows a class to hide its member variables and member
functions from other functions and objects
...
Even an instance of a class cannot access its private
members
...
WriteLine("Enter Length: ");
length = Convert
...
ReadLine());
Console
...
ToDouble(Console
...
WriteLine("Length: {0}", length);
Console
...
WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r
...
Display();
Console
...
4
Enter Width:
3
...
4
Width: 3
...
52
In the preceding example, the member variables length and width are
declared private, so they cannot be accessed from the function Main()
...
Since the member
functions AcceptDetails() andDisplay() are declared public, they can be accessed
from Main() using an instance of the Rectangle class, named r
...
This way it helps in implementing inheritance
...


Internal Access Specifier
Internal access specifier allows a class to expose its member variables and member
functions to other functions and objects in the current assembly
...

The following program illustrates this:
using System;

namespace RectangleApplication
{
class Rectangle
{
//member variables
internal double length;
internal double width;

double GetArea()
{
88

return length * width;
}
public void Display()
{
Console
...
WriteLine("Width: {0}", width);
Console
...
length = 4
...
width = 3
...
Display();
Console
...
5
Width: 3
...
75
In the preceding example, notice that the member function GetArea() is not declared
with any access specifier
...


89

Protected Internal Access Specifier
The protected internal access specifier allows a class to hide its member variables
and member functions from other class objects and functions, except a child class
within the same application
...


90

13
...
Every C# program
has at least one class with a method named Main
...
The
syntax for defining a method in C# is as follows:
(Parameter List)
{
Method Body
}

Following are the various elements of a method:


Access Specifier: This determines the visibility of a variable or a method from
another class
...
The return type is the data type
of the value the method returns
...




Method name: Method name is a unique identifier and it is case sensitive
...




Parameter list: Enclosed between parentheses, the parameters are used to
pass and receive data from a method
...
Parameters are optional;
that is, a method may contain no parameters
...


Example
Following code snippet shows a function FindMax that takes two integer values and
returns the larger of the two
...

class NumberManipulator

91

{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;

if (num1 > num2)
result = num1;
else
result = num2;

return result;
}

...
The following example
illustrates this:
using System;

namespace CalculatorApplication
{
class NumberManipulator
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;

92

if (num1 > num2)
result = num1;
else
result = num2;

return result;
}
static void Main(string[] args)
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
NumberManipulator n = new NumberManipulator();

//calling the FindMax method
ret = n
...
WriteLine("Max value is : {0}", ret );
Console
...

For example, the method FindMax belongs to the NumberManipulator class, you can
call it from another class Test
...
FindMax(a, b);

94

Console
...
ReadLine();

}
}
}

When the above code is compiled and executed, it produces the following result:
Max value is : 200

Recursive Method Call
A method can call itself
...
Following is an example that
calculates factorial for a given number using a recursive function:
using System;

namespace CalculatorApplication
{
class NumberManipulator
{
public int factorial(int num)
{
/* local variable declaration */
int result;

if (num == 1)
{
return 1;
}
else
{

95

result = factorial(num - 1) * num;
return result;
}
}

static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
//calling the factorial method
Console
...
factorial(6));
Console
...
factorial(7));
Console
...
factorial(8));
Console
...
There are three ways that parameters can be passed to a method:

Mechanism

Description

96

Value parameters

This method copies the actual value of an argument into the
formal parameter of the function
...


Reference parameters

This method copies the reference to the memory location of
an argument into the formal parameter
...


Output parameters

This method helps in returning more than one value
...
In this
mechanism, when a method is called, a new storage location is created for each value
parameter
...
Hence, the changes made
to the parameter inside the method have no effect on the argument
...
WriteLine("Before swap, value of a : {0}", a);
Console
...
swap(a, b);

Console
...
WriteLine("After swap, value of b : {0}", b);

Console
...


98

Passing Parameters by Reference
A reference parameter is a reference to a memory location of a variable
...
The reference parameters represent the same
memory location as the actual parameters that are supplied to the method
...
The following
example demonstrates this:
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public void swap(ref int x, ref int y)
{
int temp;

temp = x; /* save the value of x */
x = y;

/* put y into x */

y = temp; /* put temp into y */
}

static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
/* local variable definition */
int a = 100;
int b = 200;

Console
...
WriteLine("Before swap, value of b : {0}", b);

99

/* calling a function to swap the values */
n
...
WriteLine("After swap, value of a : {0}", a);
Console
...
ReadLine();

}
}
}

When the above code is compiled and executed, it produces the following result:
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100

It shows that the values have changed inside the swap function and this change
reflects in the Main function
...

However, using output parameters, you can return two values from a function
...


The following example illustrates this:
using System;

100

namespace CalculatorApplication
{
class NumberManipulator
{
public void getValue(out int x )
{
int temp = 5;
x = temp;
}

static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
/* local variable definition */
int a = 100;

Console
...
getValue(out a);

Console
...
ReadLine();

}
}
}

When the above code is compiled and executed, it produces the following result:
101

Before method call, value of a : 100
After method call, value of a : 5

The variable supplied for the output parameter need not be assigned a value
...
Go
through the following example, to understand this:
using System;

namespace CalculatorApplication
{
class NumberManipulator
{
public void getValues(out int x, out int y )
{
Console
...
ToInt32(Console
...
WriteLine("Enter the second value: ");
y = Convert
...
ReadLine());
}

static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
/* local variable definition */
int a , b;

/* calling a function to get the values */
n
...
WriteLine("After method call, value of a : {0}", a);

102

Console
...
ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following result:
Enter the first value:
7
Enter the second value:
8
After method call, value of a : 7
After method call, value of b : 8

103

14
...

For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null
in a Nullable variable
...
Syntax for declaring a nullable type is as follows:
< data_type> ? = null;

The following example demonstrates use of nullable data types:
using System;
namespace CalculatorApplication
{
class NullablesAtShow
{
static void Main(string[] args)
{
int? num1 = null;
int? num2 = 45;
double? num3 = new double?();
double? num4 = 3
...
WriteLine("Nullables at Show: {0}, {1}, {2}, {3}",
num1, num2, num3, num4);
Console
...
ReadLine();

}
}
}

When the above code is compiled and executed, it produces the following result:
Nullables at Show: , 45,

, 3
...

It is used for converting an operand to the type of another nullable (or not) value
type operand, where an implicit conversion is possible
...
The following
example explains this:
using System;
namespace CalculatorApplication
{
class NullablesAtShow
{

static void Main(string[] args)
{

double? num1 = null;
double? num2 = 3
...
34;
Console
...
34;
Console
...
ReadLine();

}
}
}

When the above code is compiled and executed, it produces the following result:
Value of num3: 5
...
14157

106

15
...
An
array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type stored at contigeous memory
locations
...
, and
number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and
...
A specific
element in an array is accessed by an index
...
The lowest address corresponds
to the first element and the highest address to the last element
...




[ ] specifies the rank of the array
...




arrayName specifies the name of the array
...
When the array
variable is initialized, you can assign values to the array
...
For example,
double[] balance = new double[10];

Assigning Values to an Array
You can assign values to individual array elements, by using the index number, like:
double[] balance = new double[10];
balance[0] = 4500
...
0, 4523
...
0};

You can also create and initialize an array as shown:
int [] marks = new int[5]

{ 99,

98, 92, 97, 95};

You may also omit the size of the array as shown:
int [] marks = new int[]

{ 99,

98, 92, 97, 95};

You can copy an array variable into another target array variable
...
For example, for an int array all elements
are initialized to 0
...
This is done by placing the index
of the element within square brackets after the name of the array
...
WriteLine("Element[{0}] = {1}", j, n[j]);
}
Console
...
You
can also use a foreach statement to iterate through an array
...
WriteLine("Element[{0}] = {1}", i, j);
i++;
}
Console
...
The simplest form
of the multidimensional array is the two-dimensional
array
...


Passing
functions

arrays

to

You can pass to the function a pointer to an array by
specifying the array's name without an index
...


The Array Class

Defined in System namespace, it is the base class to all
arrays, and provides various properties and methods for
working with arrays
...
Multi-dimensional arrays are also called
rectangular array
...
A 2dimensional array is a list of one-dimensional arrays
...
Following is a 2-dimensional array, which contains 3 rows and
4 columns:

112

Thus, every element in the array a is identified by an element name of the form a[ i
, j ], where a is the name of the array, and i and j are the subscripts that uniquely
identify each element in array a
...
The following array is with 3 rows and each row has 4 columns
...
That is, row
index and column index of the array
...
You can verify
it in the above diagram
...
WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
}
}
Console
...
You can declare a jagged array named
scores of type int as:
int [][] scores;

Declaring an array, does not create the array in memory
...
Length; i++)
{
scores[i] = new int[4];
}

You can initialize a jagged array as:
int[][] scores = new int[2][]{new int[]{92,93,94},new int[]{85,66,87,88}};

Where, scores is an array of two arrays of integers - scores[0] is an array of 3 integers
and scores[1] is an array of 4 integers
...
WriteLine("a[{0}][{1}] = {2}", i, j, a[i][j]);
}
}
Console
...
The following example
demonstrates this:
using System;

namespace ArrayApplication
{
class MyArray
{
double getAverage(int[] arr, int size)
{
int i;
double avg;
int sum = 0;

for (i = 0; i < size; ++i)
{
sum += arr[i];
}

avg = (double)sum / size;
return avg;
}
static void Main(string[] args)
{
MyArray app = new MyArray();
/* an int array with 5 elements */
int [] balance = new int[]{1000, 2, 3, 17, 50};
double avg;

117

/* pass pointer to the array as an argument */
avg = app
...
WriteLine( "Average value is: {0} ", avg );
Console
...
4

Param Arrays
At times, while declaring a method, you are not sure of the number of arguments
passed as a parameter
...

The following example demonstrates this:
using System;

namespace ArrayApplication
{
class ParamArray
{
public int AddElements(params int[] arr)
{
int sum = 0;
foreach (int i in arr)
{

118

sum += i;
}
return sum;
}
}

class TestClass
{
static void Main(string[] args)
{
ParamArray app = new ParamArray();
int sum = app
...
WriteLine("The sum is: {0}", sum);
Console
...
It is defined in the System
namespace
...


Properties of the Array Class
The following table describes some of the most commonly used properties of the
Array class:

119

Property

Sr
...

1

IsFixedSize
Gets a value indicating whether the Array has a fixed size
...


3

Length
Gets a 32-bit integer that represents the total number of elements in
all the dimensions of the Array
...


5

Rank
Gets the rank (number of dimensions) of the Array
...

No,
1

Clear
Sets a range of elements in the Array to zero, to false, or to null,
depending on the element type
...
The
length is specified as a 32-bit integer
...
The index is specified as a 32-bit integer
...


5

GetLongLength
Gets a 64-bit integer that represents the number of elements in the
specified dimension of the Array
...


7

GetType
Gets the Type of the current instance
...
)

8

GetUpperBound
Gets the upper bound of the specified dimension in the Array
...

The index is specified as a 32-bit integer
...


11

Reverse(Array)
Reverses the sequence of the elements in the entire one-dimensional
Array
...
The index is specified as a 32-bit integer
...


14

ToStringk
Returns a string that represents the current object
...
)

For complete list of Array class properties and methods, please consult Microsoft
documentation on C#
...
Write("Original Array: ");
foreach (int i in list)
{
Console
...
WriteLine();

122

// reverse the array
Array
...
Write("Reversed Array: ");
foreach (int i in temp)
{
Console
...
WriteLine();

//sort the array
Array
...
Write("Sorted Array: ");
foreach (int i in list)
{
Console
...
WriteLine();

Console
...
STRINGS
In C#, you can use strings as array of characters
...
The string keyword is an
alias for theSystem
...


Creating a String Object
You can create string object using one of the following methods:


By assigning a string literal to a String variable



By using a String class constructor



By using the string concatenation operator (+)



By retrieving a property or calling a method that returns a string



By calling a formatting method to convert a value or an object to its string
representation

The following example demonstrates this:
using System;

namespace StringApplication
{
class Program
{
static void Main(string[] args)
{
//from string literal and string concatenation
string fname, lname;
fname = "Rowan";
lname = "Atkinson";

string fullname = fname + lname;
Console
...
WriteLine("Greetings: {0}", greetings);

//methods returning string
string[] sarray = { "Hello", "From", "Tutorials", "Point" };
string message = String
...
WriteLine("Message: {0}", message);

//formatting method to convert a value
DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);
string chat = String
...
WriteLine("Message: {0}", chat);
Console
...

No
...


2

Length
Gets the number of characters in the current String object
...
The following table provides some of the most commonly used methods:
Sr
...

1

Methods

public static int Compare( string strA, string strB )
Compares two specified string objects and returns an integer that
indicates their relative position in the sort order
...
However, it ignores
case if the Boolean parameter is true
...


4

public static string Concat( string str0, string str1, string str2 )
Concatenates three string objects
...

6

public bool Contains( string value )
Returns a value indicating whether the specified String object occurs
within this string
...


8

public void CopyTo( int sourceIndex, char[] destination, int
destinationIndex, int count )
Copies a specified number of characters from a specified position of
the String object to a specified position in an array of Unicode
characters
...


10

public bool Equals( string value )
Determines whether the current String object and the specified String
object have the same value
...


12

public static string Format( string format, Object arg0 )
Replaces one or more format items in a specified string with the string
representation of a specified object
...


14

public int IndexOf( string value )

127

Returns the zero-based index of the first occurrence of the specified
string in this instance
...


16

public int IndexOf( string value, int startIndex )
Returns the zero-based index of the first occurrence of the specified
string in this instance, starting search at the specified character
position
...


18

public int IndexOfAny( char[] anyOf, int startIndex )
Returns the zero-based index of the first occurrence in this instance of
any character in a specified array of Unicode characters, starting
search at the specified character position
...


20

public static bool IsNullOrEmpty( string value )
Indicates whether the specified string is null or an Empty string
...


22

public static string Join( string separator, string[] value, int
startIndex, int count )
Concatenates the specified elements of a string array, using the
specified separator between each element
...


24

public int LastIndexOf( string value )
Returns the zero-based index position of the last occurrence of a
specified string within the current string object
...


26

public string Remove( int startIndex, int count )
Removes the specified number of characters in the current string
beginning at a specified position and returns the string
...


28

public string Replace( string oldValue, string newValue )
Replaces all occurrences of a specified string in the current string
object with the specified string and returns the new string
...


30

public string[] Split( char[] separator, int count )
Returns a string array that contains the substrings in the current string
object, delimited by elements of a specified Unicode character array
...


31

public bool StartsWith( string value )

129

Determines whether the beginning of this string instance matches the
specified string
...


33

public char[] ToCharArray( int startIndex, int length )
Returns a Unicode character array with all the characters in the current
string object, starting from the specified index and up to the specified
length
...


35

public string ToUpper()
Returns a copy of this string converted to uppercase
...


You can visit MSDN library for the complete list of methods and String class
constructors
...
Compare(str1, str2) == 0)
{
Console
...
");

}
else
{
Console
...
");
}
Console
...


String Contains String:
using System;

namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str = "This is test";
if (str
...
WriteLine("The sequence 'test' was found
...
ReadKey() ;
}
}
}

When the above code is compiled and executed, it produces the following result:
The sequence 'test' was found
...
WriteLine(str);
string substr = str
...
WriteLine(substr);
}
Console
...
Join("\n", starray);
Console
...
ReadKey() ;
}
}

When the above code is compiled and executed, it produces the following result:
Down the way nights are dark
And the sun shines daily on the mountain top
I took a trip on a sailing ship
And when I reached Jamaica
I made a stop

133

134

17
...
It helps you to make a single variable
hold related data of various data types
...

Structures are used to represent a record
...
You might want to track the following attributes about each book:


Title



Author



Subject



Book ID

Defining a Structure
To define a structure, you must use the struct statement
...

For example, here is the way you can declare the Book structure:
struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
};

The following program shows the use of the structure:
using System;

struct Books
{
public string title;
public string author;

135

public string subject;
public int book_id;
};

public class testStructure
{
public static void Main(string[] args)
{

Books Book1;

/* Declare Book1 of type Book */

Books Book2;

/* Declare Book2 of type Book */

/* book 1 specification */
Book1
...
author = "Nuha Ali";
Book1
...
book_id = 6495407;

/* book 2 specification */
Book2
...
author = "Zara Ali";
Book2
...
book_id = 6495700;

/* print Book1 info */
Console
...
title);
Console
...
author);
Console
...
subject);
Console
...
book_id);

136

/* print Book2 info */
Console
...
title);
Console
...
author);
Console
...
subject);
Console
...
book_id);

Console
...
Structures in C# are quite
different from that in traditional C or C++
...




Structures can have defined constructors, but not destructors
...
The default constructor is
automatically defined and connot be changed
...


137



Structures cannot be used as a base for other structures or classes
...




Structure members cannot be specified as abstract, virtual, or protected
...
Unlike classes, structs can be instantiated
without using the New operator
...


Class versus Structure
Classes and Structures have the following basic differences:


classes are reference types and structs are value types



structures do not support inheritance



structures cannot have default constructor

In the light of the above discussions, let us rewrite the previous example:
using System;

struct Books
{
private string title;
private string author;
private string subject;
private int book_id;
public void getValues(string t, string a, string s, int id)
{
title = t;
author = a;
subject = s;
book_id = id;
}
public void display()
{

138

Console
...
WriteLine("Author : {0}", author);
Console
...
WriteLine("Book_id :{0}", book_id);
}

};

public class testStructure
{
public static void Main(string[] args)
{

Books Book1 = new Books(); /* Declare Book1 of type Book */
Books Book2 = new Books(); /* Declare Book2 of type Book */

/* book 1 specification */
Book1
...
getValues("Telecom Billing",
"Zara Ali", "Telecom Billing Tutorial", 6495700);

/* print Book1 info */
Book1
...
display();

139

Console
...
ENUMS
An enumeration is a set of named integer constants
...

C# enumerations are value data type
...


Declaring enum Variable
The general syntax for declaring an enumeration is:
enum
{
enumeration list
};

Where,


The enum_name specifies the enumeration type name
...


Each of the symbols in the enumeration list stands for an integer value, one greater
than the symbol that precedes it
...
For example:
enum Days { un, Mon, tue, Wed, thu, Fri, Sat };

Example
The following example demonstrates use of enum variable:
using System;
namespace EnumApplication
{
class EnumProgram
{
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };

141

static void Main(string[] args)
{
int WeekdayStart = (int)Days
...
Fri;
Console
...
WriteLine("Friday: {0}", WeekdayEnd);
Console
...
CLASSES
When you define a class, you define a blueprint for a data type
...
That is, what an object
of the class consists of and what operations can be performed on that object
...
The methods and variables that constitute a class are called
members of the class
...
Following is the general form of a class
definition:
class

class_name

{
// member variables
variable1;
variable2;

...

methodN(parameter_list)

143

{
// method body
}
}

Note:


Access specifiers specify the access rules for the members as well as the class
itself
...
Default access for the members is private
...




To access the class members, you use the dot (
...




The dot operator links the name of an object with the name of a member
...
0;

// Store the volume of a box here

// box 1 specification

144

Box1
...
0;
Box1
...
0;
Box1
...
0;

// box 2 specification
Box2
...
0;
Box2
...
0;
Box2
...
0;

// volume of box 1
volume = Box1
...
length * Box1
...
WriteLine("Volume of Box1 : {0}",

volume);

// volume of box 2
volume = Box2
...
length * Box2
...
WriteLine("Volume of Box2 : {0}", volume);
Console
...
It operates on any object of the
class of which it is a member, and has access to all the members of a class for that
object
...
These variables can only be accessed
using the public member functions
...
setLength(6
...
setBreadth(7
...
setHeight(5
...
setLength(12
...
setBreadth(13
...
setHeight(10
...
getVolume();
Console
...
getVolume();
Console
...
ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560

C# Constructors
A class constructor is a special member function of a class that is executed whenever
we create new objects of that class
...
Following example explains the concept of constructor:
using System;
namespace LineApplication
{
class Line
{
private double length;

// Length of a line

public Line()
{
Console
...
setLength(6
...
WriteLine("Length of line : {0}", line
...
ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
Object is being created
Length of line : 6

A default constructor does not have any parameter but if you need, a constructor
can have parameters
...

This technique helps you to assign initial value to an object at the time of its creation
as shown in the following example:
using System;
namespace LineApplication
{
class Line
{
private double length;

// Length of a line

public Line(double len)

//Parameterized constructor

149

{
Console
...
0);
Console
...
getLength());
// set line length
line
...
0);
Console
...
getLength());
Console
...
A destructor has exactly the same name as
that of the class with a prefixed tilde (~) and it can neither return a value nor can it
take any parameters
...
Destructors cannot be inherited or overloaded
...
WriteLine("Object is being created");
}
~Line() //destructor
{
Console
...
setLength(6
...
WriteLine("Length of line : {0}", line
...
When we declare a
member of a class as static, it means no matter how many objects of the class are
created, there is only one copy of the static member
...

Static variables are used for defining constants because their values can be retrieved
by invoking the class without creating an instance of it
...
You can also initialize static
variables inside the class definition
...
count();
s1
...
count();
s2
...
count();
s2
...
WriteLine("Variable num for s1: {0}", s1
...
WriteLine("Variable num for s2: {0}", s2
...
ReadKey();
}
}

153

}

When the above code is compiled and executed, it produces the following result:
Variable num for s1: 6
Variable num for s2: 6

You can also declare a member function as static
...
The static functions exist even before the object is created
...
count();
s
...
count();
Console
...
getNum());
Console
...
INHERITANCE
One of the most important concepts in object-oriented programming is inheritance
...
This also provides an opportunity to reuse the
code functionality and speeds up implementation time
...
This existing class is called the base class, and the new
class is referred to as the derived class
...
For example, mammal IS
Aanimal, dog IS-A mammal hence dog IS-A animal as well, and so on
...

The syntax used in C# for creating derived classes is as follows:
class
{

...

}

Consider a base class Shape and its derived class Rectangle:
using System;
namespace InheritanceApplication
{
class Shape
{

156

public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}

// Derived class
class Rectangle: Shape
{
public int getArea()
{
return (width * height);
}
}

class RectangleTester
{
static void Main(string[] args)
{
Rectangle Rect = new Rectangle();

Rect
...
setHeight(7);

157

// Print the area of the object
...
WriteLine("Total area: {0}",

Rect
...
ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
Total area: 35

Initializing Base Class
The derived class inherits the base class member variables and member methods
...

You can give instructions for superclass initialization in the member initialization list
...
WriteLine("Length: {0}", length);
Console
...
WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class Tabletop : Rectangle
{
private double cost;
public Tabletop(double l, double w) : base(l, w)
{ }
public double GetCost()
{
double cost;
cost = GetArea() * 70;
return cost;
}
public void Display()
{
base
...
WriteLine("Cost: {0}", GetCost());
}
}
class ExecuteRectangle
{

159

static void Main(string[] args)
{
Tabletop t = new Tabletop(4
...
5);
t
...
ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following result:
Length: 4
...
5
Area: 33
...
5

Multiple Inheritance in C#
C# does not support multiple inheritance
...
The following program demonstrates this:
using System;
namespace InheritanceApplication
{
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;

160

}
protected int width;
protected int height;
}

// Base class PaintCost
public interface PaintCost
{
int getCost(int area);

}
// Derived class
class Rectangle : Shape, PaintCost
{
public int getArea()
{
return (width * height);
}
public int getCost(int area)
{
return area * 70;
}
}
class RectangleTester
{
static void Main(string[] args)
{
Rectangle Rect = new Rectangle();
int area;

161

Rect
...
setHeight(7);
area = Rect
...

Console
...
getArea());

Console
...
getCost(area));
Console
...
POLYMORPHISM
The word polymorphism means having many forms
...

Polymorphism can be static or dynamic
...
In dynamic polymorphism , it is decided
at run-time
...
It is also called static binding
...
They are:
1
...
Operator overloading
We discuss operator overloading in next chapter
...
The
definition of the function must differ from each other by the types and/or the number
of arguments in the argument list
...

The following example shows using function print() to print different data types:
using System;
namespace PolymorphismApplication
{
class Printdata
{
void print(int i)
{
Console
...
WriteLine("Printing float: {0}" , f);
}

void print(string s)
{
Console
...
print(5);
// Call print to print float
p
...
263);
// Call print to print string
p
...
ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
Printing int: 5
Printing float: 500
...
Implementation is completed when a derived class
inherits from it
...
The derived classes have more specialized functionality
...


The following program demonstrates an abstract class:
using System;
namespace PolymorphismApplication
{
abstract class Shape
{
public abstract int area();
}
class Rectangle:

Shape

{
private int length;
private int width;
public Rectangle( int a=0, int b=0)
{
length = a;
width = b;
}
public override int area ()
{
Console
...
area();
Console
...
ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
Rectangle class area :
Area: 70

When you have a function defined in a class that you want to be implemented in an
inherited class(es), you use virtual functions
...

Dynamic polymorphism is implemented by abstract classes and virtual functions
...
WriteLine("Parent class area :");
return 0;
}
}
class Rectangle: Shape
{
public Rectangle( int a=0, int b=0): base(a, b)
{

}
public override int area ()
{
Console
...
WriteLine("Triangle class area :");
return (width * height / 2);
}
}
class Caller
{
public void CallArea(Shape sh)
{
int a;
a = sh
...
WriteLine("Area: {0}", a);
}
}
class Tester
{

static void Main(string[] args)
{
Caller c = new Caller();
Rectangle r = new Rectangle(10, 7);
Triangle t = new Triangle(10, 5);
c
...
CallArea(t);
Console
...
OPERATOR OVERLOADING
You can redefine or overload most of the built-in operators available in C#
...
Overloaded operators
are functions with special names the keyword operator followed by the symbol for
the operator being defined
...

For example, go through the following function:
public static Box operator+ (Box b, Box c)
{
Box box = new Box();
box
...
length + c
...
breadth = b
...
breadth;
box
...
height + c
...
It adds the attributes of two Box objects and returns the resultant Box object
...

public static Box operator+ (Box b, Box c)
{
Box box = new Box();
box
...
length + c
...
breadth = b
...
breadth;
box
...
height + c
...
0;

// Store the volume of a box here

// box 1 specification
Box1
...
0);
Box1
...
0);
Box1
...
0);

// box 2 specification
Box2
...
0);
Box2
...
0);
Box2
...
0);

// volume of box 1
volume = Box1
...
WriteLine("Volume of Box1 : {0}", volume);

// volume of box 2
volume = Box2
...
WriteLine("Volume of Box2 : {0}", volume);

172

// Add two object as follows:
Box3 = Box1 + Box2;

// volume of box 3
volume = Box3
...
WriteLine("Volume of Box3 : {0}", volume);
Console
...


+, -, *, /, %

These binary operators take one operand and can be
overloaded
...


173

+=, -=, *=, /=, %=

The assignment operators cannot be overloaded
...
, ?:, ->, new, is, sizeof,
typeof

These operators cannot be overloaded
...

public static Box operator+ (Box b, Box c)
{
Box box = new Box();
box
...
length + c
...
breadth = b
...
breadth;
box
...
height + c
...
length == rhs
...
height == rhs
...
breadth == rhs
...
length != rhs
...
height != rhs
...
breadth != rhs
...
length < rhs
...
height
< rhs
...
breadth < rhs
...
length > rhs
...
height
> rhs
...
breadth > rhs
...
length <= rhs
...
height
<= rhs
...
breadth <= rhs
...
length >= rhs
...
height
>= rhs
...
breadth >= rhs
...
Format("({0}, {1}, {2})", length, breadth, height);
}

}

class Tester

177

{
static void Main(string[] args)
{
Box Box1 = new Box();

// Declare Box1 of type Box

Box Box2 = new Box();

// Declare Box2 of type Box

Box Box3 = new Box();

// Declare Box3 of type Box

Box Box4 = new Box();
double volume = 0
...
setLength(6
...
setBreadth(7
...
setHeight(5
...
setLength(12
...
setBreadth(13
...
setHeight(10
...
WriteLine("Box 1: {0}", Box1
...
WriteLine("Box 2: {0}", Box2
...
getVolume();
Console
...
getVolume();

178

Console
...
WriteLine("Box 3: {0}", Box3
...
getVolume();
Console
...
WriteLine("Box1 is greater than Box2");
else
Console
...
WriteLine("Box1 is less than Box2");
else
Console
...
WriteLine("Box1 is greater or equal to Box2");
else
Console
...
WriteLine("Box1 is less or equal to Box2");
else
Console
...
WriteLine("Box1 is not equal to Box2");
else

179

Console
...
WriteLine("Box3 is equal to Box4");
else
Console
...
ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
Box 1: (6, 7, 5)
Box 2: (12, 13, 10)
Volume of Box1 : 210
Volume of Box2 : 1560
Box 3: (18, 20, 15)
Volume of Box3 : 5400
Box1 is not greater than Box2
Box1 is less than Box2
Box1 is not greater or equal to Box2
Box1 is less or equal to Box2
Box1 is not equal to Box2
Box3 is equal to Box4

180

23
...
The interface defines the 'what' part of the syntactical
contract and the deriving classes define the 'how' part of the syntactical contract
...
Interfaces contain only the declaration of the members
...
It often helps in providing
a standard structure that the deriving classes would follow
...


Declaring Interfaces
Interfaces are declared using the interface keyword
...

Interface statements are public by default
...
Collections
...
Linq;
using System
...
0;
}
public Transaction(string c, string d, double a)
{
tCode = c;
date = d;
amount = a;
}
public double getAmount()
{
return amount;
}
public void showTransaction()

182

{
Console
...
WriteLine("Date: {0}", date);
Console
...
00);
Transaction t2 = new Transaction("002", "9/10/2012", 451900
...
showTransaction();
t2
...
ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900

183

24
...
The class names declared in one namespace does not conflict with the
same class names declared in another
...
item_name;

The following program demonstrates use of namespaces:
using System;
namespace first_space
{
class namespace_cl
{
public void func()
{
Console
...
WriteLine("Inside second_space");
}
}
}
class TestClass
{
static void Main(string[] args)
{
first_space
...
namespace_cl();
second_space
...
namespace_cl();
fc
...
func();
Console
...
For example, we are using the System namespace in our programs
...
We just write:

185

Console
...
Console
...

This directive tells the compiler that the subsequent code is making use of names in
the specified namespace
...
WriteLine("Inside first_space");
}
}
}
namespace second_space
{
class efg
{
public void func()
{
Console
...
func();
sc
...
ReadKey();
}
}

When the above code is compiled and executed, it produces the following result:
Inside first_space
Inside second_space

Nested Namespaces
You can define one namespace inside another namespace as follows:
namespace namespace_name1
{
// code declarations
namespace namespace_name2
{
// code declarations
}
}

187

You can access members of nested namespace by using the dot (
...
second_space;

namespace first_space
{
class abc
{
public void func()
{
Console
...
WriteLine("Inside second_space");
}
}
}
}

class TestClass
{

188

static void Main(string[] args)
{
abc fc = new abc();
efg sc = new efg();
fc
...
func();
Console
...
PREPROCESSOR DIRECTIVES
The preprocessor directives give instruction to the compiler to preprocess the
information before actual compilation starts
...
Preprocessor directives are not statements,
so they do not end with a semicolon (;)
...
In C# the preprocessor directives are used to help in
conditional compilation
...
A preprocessor directive must be the only instruction on a line
...


#define

It defines a sequence of characters, called symbol
...


#if

It allows testing a symbol or symbols to see if they evaluate to true
...


#elif

It allows creating a compound conditional directive
...


#line

It lets you modify the compiler's line number and (optionally) the
file name output for errors and warnings
...


#warning

It allows generating a level one warning from a specific location in
your code
...


#endregion

It marks the end of a #region block
...

#define lets you define a symbol such that, by using the symbol as the expression
passed to the #if directive, the expression evaluates to true
...
WriteLine("PI is defined");
#else
Console
...
ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:

191

PI is defined

Conditional Directives
You can use the #if directive to create a conditional directive
...
If they
do evaluate to true, the compiler evaluates all the code between the #if and the next
directive
...


Where, symbol is the name of the symbol you want to test
...

The operator symbol is the operator used for evaluating the symbol
...
Conditional directives
are used for compiling code for a debug build or when compiling for a specific
configuration
...

The following program demonstrates use of conditional directives:
#define DEBUG
#define VC_V10
using System;
public class TestClass
{
public static void Main()
{

#if (DEBUG && !VC_V10)
Console
...
WriteLine("VC_V10 is defined");
#elif (DEBUG && VC_V10)
Console
...
WriteLine("DEBUG and VC_V10 are not defined");
#endif
Console
...
REGULAR EXPRESSIONS
A regular expression is a pattern that could be matched against an input text
...
Net framework provides a regular expression engine that allows such matching
...


Constructs for Defining Regular Expressions
There are various categories of characters, operators, and constructs that lets you to
define regular expressions
...



Character escapes



Character classes



Anchors



Grouping constructs



Quantifiers



Backreference constructs



Alternation constructs



Substitutions



Miscellaneous constructs

Character Escapes
These are basically the special characters or escape characters
...

The following table lists the escape characters:
Description

Escapech
aracter
\a

Matches
\u0007
...


a

bell

character,

Pattern

Matches

\a

"\u0007"
"Warning!"
'\u0007'

in
+

[\b]{3,}

"\b\b\b\b"
"\b\b\b\b"

in

194

\t

Matches a tab, \u0009
...
(\r is not equivalent to
the newline character, \n
...
"

\v

Matches a vertical tab, \u000B
...


[\f]{2,}

"\f\f\f" in "\f\f\f"

\n

Matches a new line, \u000A
...
"

\e

Matches an escape, \u001B
...


\w\040\w

"a b", "c d" in "a bc
d"

\x nn

Uses
hexadecimal
representation to specify a
character
(nn
consists
of
exactly two digits)
...


\cC

"\x0003"
in
"\x0003" (Ctrl-C)

\u nnnn

Matches a Unicode character by
using
hexadecimal
representation (exactly four
digits, as represented by nnnn)
...


\d+[\+x\*]\d+\d+[\+x\*\d+

"2+2" and "3*9" in
"(2+2) * 3*9"

Birds

in

in

195

Character Classes
A character class matches any one of a set of characters
...

By
default, the match is casesensitive
...
By default,
characters incharacter_group
are case-sensitive
...


(\w+)\t

"Name\t",
"Addr\t"
in
"Name\tAddr\t"


...


a
...


\p{Lu}

"C", "L" in "City
Lights"

\P{ name }

Matches any single character
that is not in the Unicode
general category or named
block specified by name
...


\w

"R", "o", "m"
and
"1"
in
"Room#1"

\W

Matches
character
...


white-space

\w\s

"D " in "ID A1
...


\s\S

" _"
__ctr"

\d

Matches any decimal digit
...


\D

" ", "=", " ", "I",
"V" in "4 = IV"

in

"int

Anchors Regular Expressions
Anchors allow a match to succeed or fail depending on the current position in the
string
...


the

^\d{3}

"567"
777-"

$

The match must occur at the end of
the string or before \n at the end of
the line or string
...


\A\w{3}

"Code" in "Code007-"

\Z

The match must occur at the end of
the string or before \n at the end of
the string
...


-\d{3}\z

"-333" in "-901333"

\G

The match must occur at the point
where the previous match ended
...


\w

"R", "o", "m" and
"1" in "Room#1"

\B

The match must
a\b boundary
...
The following table lists the grouping constructs:
Grouping
construct

Description

( subexpression )

Captures the matched
subexpression
and
assigns it a zero-based
ordinal number
...


(?<
double>\w)\k<
double>

"ee" in "deep"

(?< name1 name2
>subexpression)

Defines a balancing group
definition
...


Write(?:Line)?

"WriteLine"
in
"Console
...


A\d{2}(?i:\w+)\b

"A12xl",
"A12XL"
in
"A12xl
A12XL
a12xl"

matched
into
a

Pattern

Matches

198

(?=
subexpression)

Zero-width
positive
lookahead assertion
...
)

"is", "ran", and
"out" in "He is
...

The sun is out
...


\b(?!un)\w+\b

"sure", "used"
in "unsure sure
unity used"

(?<
=subexpression)

Zero-width
positive
lookbehind assertion
...


(?< !19)\d{2}\b

"ends", "ender"
in "end sends
endure lender"

(?>
subexpression)

Nonbacktracking
(or
"greedy") subexpression
...

Quantifier

Description

Pattern

Matches

*

Matches the previous element zero
or more times
...
\d

"
...
9", "219
...


"be+"

"bee" in "been", "be"
in "bent"

?

Matches the previous element zero
or one time
...


element

",\d{3}"

",043" in "1,043
...


"\d{2,}"

"166", "29", "1930"

{n,m}

Matches the previous element at
least n times, but no more than m
times
...


\d*?\
...
0", "19
...
9"

+?

Matches the previous element one
or more times, but as few times as
possible
...


"rai??n"

"ran", "rain"

{ n }?

Matches the preceding element
exactly n times
...
6",
",876", ",543", and
",210"
in
"9,876,543,210"

{ n ,}?

Matches the previous element at
least n times, but as few times as
possible
...


"\d{3,5}?"

"166",
"17668"
"193",
"024"
in
"193024"

Backreference Constructs
Backreference constructs allow a previously matched sub-expression to be identified
subsequently in the same regular expression
...
Matches the value of
a numbered subexpression
...
Matches the
value of a named expression
...
The
following table lists the alternation constructs:
Alternation
construct

Description

Pattern

Matches

|

Matches
any
one
element separated by
the vertical bar (|)
character
...
"

(?(
expression
)yes | no )

Matches
yes
if
expression matches;
otherwise,
matches
the optional no part
...


(?(A)A\d{2}\b|\b\d{3}\b)

"A10", "910"
in "A10 C103
910"

(?(
name
)yes | no )

Matches yes if the
named capture name
has
a
match;
otherwise,
matches
the optional no
...
+?"
|\S+\s)

Dogs
...
jpg"
in "Dogs
...
jpg"
"

201

Substitution
Substitutions are used in replacement patterns
...

Substitutes the \b(?<
${word2}
substring
word1>\w+) ${word1}
matched by the (\s)(?<
namedgroupna word2>\w+)
me
...

D
Substitutes
a (\$*(\d*(\
...

Substitutes all B+
$`
the text of the
input
string
before
the
match
...

Substitutes the B+(C+)
$+
last group that
was captured
...


Input
string

Resulting
string

"one two" "two one"

"one two" "two one"

"103
USD"
"$1
...
30**
"

Miscellaneous Constructs
The following table lists various miscellaneous constructs:
Construct
(?imnsximnsx)

Definition

Example

Sets or disables options such as case
insensitivity in the middle of a
pattern
...
The comment ends
at the first closing parenthesis
...
The comment
starts at an unescaped # and
continues to the end of the line
...
It has the following
commonly used methods:
Sr
...

1

Methods

public bool IsMatch( string input )
Indicates whether the regular expression specified in the Regex constructor
finds a match in a specified input string
...


3

public static bool IsMatch( string input, string pattern )
Indicates whether the specified regular expression finds a match in the
specified input string
...


5

public string Replace( string input, string replacement )
In a specified input string, replaces all strings that match a regular
expression pattern with a specified replacement string
...

For the complete list of methods and properties, please read the Microsoft
documentation on C#
...
Text
...
WriteLine("The Expression: " + expr);
MatchCollection mc = Regex
...
WriteLine(m);
}
}
static void Main(string[] args)
{
string str = "A Thousand Splendid Suns";

Console
...
ReadKey();

204

}
}
}

When the above code is compiled and executed, it produces the following result:
Matching words that start with 'S':
The Expression: \bS\S*
Splendid
Suns

Example 2
The following example matches words that start with 'm' and ends with 'e':
using System;
using System
...
RegularExpressions;

namespace RegExApplication
{
class Program
{
private static void showMatch(string text, string expr)
{
Console
...
Matches(text, expr);
foreach (Match m in mc)
{
Console
...
WriteLine("Matching words start with 'm' and ends with 'e':");
showMatch(str, @"\bm\S*e\b");
Console
...
Text
...
Replace(input, replacement);

Console
...
WriteLine("Replacement String: {0}", result);
Console
...
EXCEPTION HANDLING
An exception is a problem that arises during the execution of a program
...

Exceptions provide a way to transfer control from one part of a program to another
...



try: A try block identifies a block of code for which particular exceptions is
activated
...




catch: A program catches an exception with an exception handler at the place
in a program where you want to handle the problem
...




finally: The finally block is used to execute a given set of statements, whether
an exception is thrown or not thrown
...




throw: A program throws an exception when a problem shows up
...


Syntax
Assuming a block raises an exception, a method catches an exception using a
combination of the try and catch keywords
...
Code within a try/catch block is referred to
as protected code, and the syntax for using try/catch looks like the following:
try
{
// statements causing exception
}
catch( ExceptionName e1 )
{
// error handling code
}
catch( ExceptionName e2 )
{
// error handling code

208

}
catch( ExceptionName eN )
{
// error handling code
}
finally
{
// statements to be executed
}

You can list down multiple catch statements to catch different type of exceptions in
case your try block raises more than one exception in different situations
...
The exception classes in C# are mainly
directly or indirectly derived from the System
...
Some of the
exception
classes
derived
from
the
System
...
ApplicationException and System
...

The System
...
Hence the exceptions defined by the programmers should
derive from this class
...
SystemException class is the base class for all predefined system
exception
...
SystemException class:
Exception Class

Description

System
...
IOException

Handles I/O errors
...
IndexOutOfRangeException

Handles errors generated when a method
refers to an array index out of range
...
ArrayTypeMismatchException

Handles errors generated when type is
mismatched with the array type
...
NullReferenceException

Handles errors generated from deferencing
a null object
...
DivideByZeroException

Handles errors generated from dividing a
dividend with zero
...
InvalidCastException

Handles
errors
typecasting
...
OutOfMemoryException

Handles errors generated from insufficient
free memory
...
StackOverflowException

Handles errors
overflow
...
Using these blocks the core program statements are separated from
the error-handling statements
...
Following is an example of throwing an
exception when dividing by zero condition occurs:
using System;
namespace ErrorHandlingApplication
{
class DivNumbers
{
int result;
DivNumbers()
{
result = 0;
}
public void division(int num1, int num2)
{

210

try
{
result = num1 / num2;
}
catch (DivideByZeroException e)
{
Console
...
WriteLine("Result: {0}", result);
}

}
static void Main(string[] args)
{
DivNumbers d = new DivNumbers();
d
...
ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
Exception caught: System
...

at
...
User-defined exception classes are derived
from the ApplicationException class
...
showTemp();
}
catch(TempIsZeroException e)
{
Console
...
Message);
}
Console
...
WriteLine("Temperature: {0}", temperature);
}
}
}

When the above code is compiled and executed, it produces the following result:
TempIsZeroException: Zero Temperature found

Throwing Objects
You can throw an object if it is either directly or indirectly derived from the
System
...
You can use a throw statement in the catch block to throw
the present object as:
Catch(Exception e)
{

...
FILE I/O
A file is a collection of data stored in a disk with a specific name and a directory path
...

The stream is basically the sequence of bytes passing through the communication
path
...

The input stream is used for reading data from file (read operation) and the output
stream is used for writing into the file (write operation)
...
IO namespace has various classes that are used for performing
numerous operations with files, such as creating and deleting files, reading from or
writing to a file, closing a file etc
...
IO namespace:
I/O Class

Description

BinaryReader

Reads primitive data from a binary stream
...


BufferedStream

A temporary storage for a stream of bytes
...


DirectoryInfo

Used for performing operations on directories
...


File

Helps in manipulating files
...


FileStream

Used to read from and write to any location in a file
...


Path

Performs operations on path information
...


StreamWriter

Is used for writing characters to a stream
...


StringWriter

Is used for writing into a string buffer
...
IO namespace helps in reading from, writing to
and closing files
...

You need to create a FileStream object to create a new file or open an existing file
...
txt as
shown:
FileStream F = new FileStream("sample
...
Open, FileAccess
...
Read);

Parameter
FileMode

Description
The FileMode enumerator defines various methods for opening
files
...



Create: It creates a new file
...




Open: It opens an existing file
...




Truncate: It opens an existing file and truncates its size to
zero bytes
...


FileShare

FileShare enumerators have the following members:
 Inheritable: It allows a file handle to pass inheritance to the
child processes


None: It declines sharing of the current file



Read: It allows opening the file for reading



ReadWrite: It allows opening the file for reading and writing



Write: It allows opening the file for writing

Example
The following program demonstrates use of the FileStream class:
using System;
using System
...
dat",
FileMode
...
ReadWrite);

for (int i = 1; i <= 20; i++)
{

216

F
...
Position = 0;

for (int i = 0; i <= 20; i++)
{
Console
...
ReadByte() + " ");
}
F
...
ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1

Advanced File Operations in C#
The preceding example provides simple file operations in C#
...
IO classes, you need to know the commonly used
properties and methods of these classes
...


files
files
...


files
files
...


Reading from and Writing to Text Files
The StreamReader and StreamWriter classes are used for reading from and writing
data to text files
...


The StreamReader Class
The StreamReader class also inherits from the abstract base class TextReader that
represents a reader for reading series of characters
...
No
...


2

public override int Peek()
Returns the next available character but does not consume it
...


Example
The following example demonstrates reading a text file named Jamaica
...
The file
reads:
Down the way where the nights are gay
And the sun shines daily on the mountain top
I took a trip on a sailing ship
And when I reached Jamaica
I made a stop

218

using System;
using System
...

// The using statement also closes the StreamReader
...
txt"))
{
string line;

// Read and display lines from the file until
// the end of the file is reached
...
ReadLine()) != null)
{
Console
...

Console
...
WriteLine(e
...
ReadKey();
}
}
}

Guess what it displays when you compile and run the program!

The StreamWriter Class
The StreamWriter class inherits from the abstract class TextWriter that represents
a writer, which can write a series of character
...

No
...


2

public override void Flush()
Clears all buffers for the current writer and causes any buffered data
to be written to the underlying stream
...
(Inherited from TextWriter
...


5

public virtual void Write( decimal value )
Writes the text representation of a decimal value to the text string or
stream
...


7

public virtual void Write( int value )
Writes the text representation of a 4-byte signed integer to the text
string or stream
...


9

public virtual void WriteLine()
Writes a line terminator to the text string or stream
...


Example
The following example demonstrates writing text data into a file using the
StreamWriter class:
using System;
using System
...
txt"))
{

221

foreach (string s in names)
{
sw
...

string line = "";
using (StreamReader sr = new StreamReader("names
...
ReadLine()) != null)
{
Console
...
ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
Zara Ali
Nuha Ali

Reading from and Writing into Binary files
The BinaryReader and BinaryWriter classes are used for reading from and writing
to a binary file
...

A BinaryReader object is created by passing a FileStream object to its constructor
...

Sr
...


Methods

1

public override void Close()
It closes the BinaryReader object and the underlying stream
...


3

public virtual bool ReadBoolean()
Reads a Boolean value from the current stream and advances the current
position of the stream by one byte
...


5

public virtual byte[] ReadBytes( int count )
Reads the specified number of bytes from the current stream into a byte
array and advances the current position by that number of bytes
...


7

public virtual char[] ReadChars( int count )
Reads the specified number of characters from the current stream, returns
the data in a character array, and advances the current position in
accordance with the Encoding used and the specific character being read
from the stream
...


223

9

public virtual int ReadInt32()
Reads a 4-byte signed integer from the current stream and advances the
current position of the stream by four bytes
...
The string is prefixed with the
length, encoded as an integer seven bits at a time
...
A BinaryWriter
object is created by passing a FileStream object to its constructor
...

Sr
...


Functions

1

public override void Close()
It closes the BinaryWriter object and the underlying stream
...


3

public virtual long Seek( int offset, SeekOrigin origin )
Sets the position within the current stream
...


5

public virtual void Write( byte value )
Writes an unsigned byte to the current stream and advances the
stream position by one byte
...


224

7

public virtual void Write( char ch )
Writes a Unicode character to the current stream and advances the
current position of the stream in accordance with the Encoding used
and the specific characters being written to the stream
...


9

public virtual void Write( double value )
Writes an eight-byte floating-point value to the current stream and
advances the stream position by eight bytes
...


11

public virtual void Write( string value )
Writes a length-prefixed string to this stream in the current encoding
of the BinaryWriter, and advances the current position of the stream
in accordance with the encoding used and the specific characters being
written to the stream
...


Example
The following example demonstrates reading and writing binary data:
using System;
using System
...
14157;
bool b = true;
string s = "I am happy";
//create the file
try
{
bw = new BinaryWriter(new FileStream("mydata",
FileMode
...
WriteLine(e
...
");
return;
}
//writing into the file
try
{
bw
...
Write(d);
bw
...
Write(s);
}
catch (IOException e)
{

226

Console
...
Message + "\n Cannot write to file
...
Close();
//reading from the file
try
{
br = new BinaryReader(new FileStream("mydata",
FileMode
...
WriteLine(e
...
");
return;
}
try
{
i = br
...
WriteLine("Integer data: {0}", i);
d = br
...
WriteLine("Double data: {0}", d);
b = br
...
WriteLine("Boolean data: {0}", b);
s = br
...
WriteLine("String data: {0}", s);
}
catch (IOException e)
{

227

Console
...
Message + "\n Cannot read from file
...
Close();
Console
...
14157
Boolean data: True
String data: I am happy

Windows File System
C# allows you to work with the directories and files using various directory and file
related classes such as the DirectoryInfo class and the FileInfo class
...
It has various
methods for creating, moving, and browsing through directories and subdirectories
...

Following are some commonly used properties of the DirectoryInfo class:
Properties

Sr
...

1

Attributes
Gets the attributes for the current file or directory
...


228

3

Exists
Gets a Boolean value indicating whether the directory exists
...


5

FullName
Gets the full path of the directory or file
...


7

Name
Gets the name of this DirectoryInfo instance
...

No
...


2

public DirectoryInfo CreateSubdirectory( string path )
Creates a subdirectory or subdirectories on the specified path
...


3

public override void Delete()
Deletes this DirectoryInfo if it is empty
...


5

public FileInfo[] GetFiles()

229

Returns a file list from the current directory
...


The FileInfo Class
The FileInfo class is derived from the FileSystemInfo class
...
This class cannot be inherited
...

No
...


2

CreationTime
Gets the creation time of the current file
...


4

Exists
Gets a Boolean value indicating whether the file exists
...


6

FullName
Gets the full path of the file
...


230

8

LastWriteTime
Gets the time of the last written activity of the file
...


10

Name
Gets the name of the file
...

No
...


2

public FileStream Create()
Creates a file
...


4

public void MoveTo( string destFileName )
Moves a specified file to a new location, providing the option to specify
a new file name
...


6

public FileStream Open( FileMode mode, FileAccess access )
Opens a file in the specified mode with read, write, or read/write
access
...

8

public FileStream OpenRead()
Creates a read-only FileStream

9

public FileStream OpenWrite()
Creates a write-only FileStream
...


of

properties

and

methods,

please

visit

Microsoft's

C#

Example
The following example demonstrates the use of the above-mentioned classes:
using System;
using System
...
GetFiles();
foreach (FileInfo file in f)
{
Console
...
Name, file
...
ReadKey();
}
}
}

When you compile and run the program, it displays the names of files and their
respective sizes in the Windows directory
...
ATTRIBUTES
An attribute is a declarative tag that is used to convey information to runtime about
the behaviors of various elements like classes, methods, structures, enumerators,
assemblies etc
...
You can add declarative information to a program
by using an attribute
...

Attributes are used for adding metadata, such as compiler instruction and other
information such as comments, description, methods and classes to a program
...
Net Framework provides two types of attributes: the pre-defined attributes
and custom builtattributes
...
)]
element

Name of the attribute and its values are specified within the square brackets, before
the element to which the attribute is applied
...


Predefined Attributes
The
...
AttributeUsage
2
...
Obsolete

AttributeUsage
The pre-defined attribute AttributeUsage describes how a custom attribute class
can be used
...

Syntax for specifying this attribute is as follows:
[AttributeUsage(
validon,
AllowMultiple=allowmultiple,

234

Inherited=inherited
)]

Where,


The parameter validon specifies the language elements on which the attribute
can
be
placed
...
The default value is AttributeTargets
...




The
parameter
allowmultiple
(optional)
provides
value
for
the AllowMultipleproperty of this attribute, a Boolean value
...
The default is false (single-use)
...
If it is true, the attribute is inherited by derived
classes
...


For example,
[AttributeUsage(AttributeTargets
...
Constructor |
AttributeTargets
...
Method |
AttributeTargets
...

It causes conditional compilation of method calls, depending on the specified value
such as Debug or Trace
...

Syntax for specifying this attribute is as follows:
[Conditional(
conditionalSymbol
)]

For example,
[Conditional("DEBUG")]

235

The following example demonstrates the attribute:
#define DEBUG
using System;
using System
...
WriteLine(msg);
}
}
class Test
{
static void function1()
{
Myclass
...
");
function2();
}
static void function2()
{
Myclass
...
");
}
public static void Main()
{
Myclass
...
");
function1();
Console
...
It enables
you to inform the compiler to discard a particular target element
...

Syntax for specifying this attribute is as follows:
[Obsolete(
message
)]
[Obsolete(
message,
iserror
)]

Where,


The parameter message, is a string describing the reason why the item is
obsolete and what to use instead
...
If its value is true, the compiler
should treat the use of the item as an error
...


The following program demonstrates this:
using System;
public class MyClass
{
[Obsolete("Don't use OldMethod, use NewMethod instead", true)]

237

static void OldMethod()
{
Console
...
WriteLine("It is the new method");
}
public static void Main()
{
OldMethod();
}
}

When you try to compile the program, the compiler gives an error message stating:
Don't use OldMethod, use NewMethod instead

Creating Custom Attributes
The
...
This information can be
related to any target element depending upon the design criteria and application
need
...

2
...

4
...
Metadata is data about data or information used for describing
other data
...

This we will discuss in the next chapter
...
Attribute class
...
Class |
AttributeTargets
...
Field |
AttributeTargets
...
Property,
AllowMultiple = true)]

public class DeBugInfo : System
...


Constructing the Custom Attribute
Let us construct a custom attribute named DeBugInfo, which stores the information
obtained by debugging any program
...
Hence the bug number, developer’s
name, and date of review are the positional parameters of the DeBugInfo class and
the message is an optional or named parameter
...
The positional parameters should
be passed through the constructor
...
Class |
AttributeTargets
...
Field |
AttributeTargets
...
Property,
AllowMultiple = true)]

public class DeBugInfo : System
...
bugNo = bg;
this
...
lastReview = d;
}

public int BugNo
{
get
{
return bugNo;
}
}
public string Developer
{
get
{
return developer;

240

}
}
public string LastReview
{
get
{
return lastReview;
}
}
public string Message
{
get
{
return message;
}
set
{
message = value;
}
}
}

Applying the Custom Attribute
The attribute is applied by placing it immediately before its target:
[DeBugInfo(45, "Zara Ali", "12/8/2012", Message = "Return type mismatch")]
[DeBugInfo(49, "Nuha Ali", "10/10/2012", Message = "Unused variable")]
class Rectangle
{
//member variables

241

protected double length;
protected double width;
public Rectangle(double l, double w)
{
length = l;
width = w;
}
[DeBugInfo(55, "Zara Ali", "19/10/2012",
Message = "Return type mismatch")]
public double GetArea()
{
return length * width;
}
[DeBugInfo(56, "Zara Ali", "19/10/2012")]
public void Display()
{
Console
...
WriteLine("Width: {0}", width);
Console
...


242

30
...
The classes
that give access to the metadata of a running program are in
the System
...

The System
...


Applications of Reflection
Reflection has the following applications:


It allows view attribute information at runtime
...




It allows late binding to methods and properties



It allows creating new types at runtime and then performs some tasks using
those types
...

The MemberInfo object of the System
...
To do this, you define an object
of the target class, as:
System
...
MemberInfo info = typeof(MyClass);

The following program demonstrates this:
using System;

[AttributeUsage(AttributeTargets
...
Attribute
{
public readonly string Url;

243

public string Topic

// Topic is a named parameter

{
get
{
return topic;
}
set
{

topic = value;
}
}

public HelpAttribute(string url)

// url is a positional parameter

{
this
...
Reflection
...
GetCustomAttributes(true);
for (int i = 0; i < attributes
...
Console
...
ReadKey();

}
}
}

When it is compiled and run, it displays the name of the custom attributes attached
to the class MyClass:
HelpAttribute

Example
In this example, we use the DeBugInfo attribute created in the previous chapter and
use reflection to read metadata in the Rectangle class
...
Reflection;
namespace BugFixApplication
{
//a custom attribute BugFix to be
//assigned to a class and its members
[AttributeUsage(AttributeTargets
...
Constructor |
AttributeTargets
...
Method |
AttributeTargets
...
Attribute
{
private int bugNo;
private string developer;
private string lastReview;
public string message;

public DeBugInfo(int bg, string dev, string d)
{
this
...
developer = dev;
this
...
WriteLine("Length: {0}", length);
Console
...
WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle

class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle(4
...
5);
r
...
GetCustomAttributes(false))
{
DeBugInfo dbi = (DeBugInfo)attributes;
if (null != dbi)
{
Console
...
BugNo);
Console
...
Developer);
Console
...
LastReview);
Console
...
Message);
}
}

//iterating through the method attribtues
foreach (MethodInfo m in type
...
GetCustomAttributes(true))
{
DeBugInfo dbi = (DeBugInfo)a;
if (null != dbi)
{
Console
...
BugNo, m
...
WriteLine("Developer: {0}", dbi
...
WriteLine("Last Reviewed: {0}",
dbi
...
WriteLine("Remarks: {0}", dbi
...
ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following result:
Length: 4
...
5
Area: 33
...
PROPERTIES
Properties are named members of classes,
variables or methods in a class or structures
extension of fields and are accessed
use accessors through which the values of the
manipulated
...
Member
are called Fields
...
They
private fields can be read, written, or

Properties do not name the storage locations
...

For example, let us have a class named Student, with private fields for age, name,
and code
...


Accessors
The accessor of a property contains the executable statements that helps in getting
(reading or computing) or setting (writing) the property
...
For example:
// Declare a Code property of type string:
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}

// Declare a Name property of type string:

251

public string Name
{
get
{
return name;
}
set
{
name = value;
}
}

// Declare a Age property of type int:
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}

Example
The following example demonstrates use of properties:
using System;
namespace tutorialspoint
{

252

class Student
{

private string code = "N
...
Code = "001";
s
...
Age = 9;
Console
...
Age += 1;
Console
...
ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
Student Info: Code = 001, Name = Zara, Age = 9
Student Info: Code = 001, Name = Zara, Age = 10

Abstract Properties
An abstract class may have an abstract property, which should be implemented in
the derived class
...
A";
private string name = "N
...
Code = "001";
s
...
Age = 9;
Console
...
Age += 1;
Console
...
ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
Student Info: Code = 001, Name = Zara, Age = 9
Student Info: Code = 001, Name = Zara, Age = 10

258

32
...
When you define an
indexer for a class, this class behaves similar to a virtual array
...


Syntax
A one dimensional indexer has the following syntax:
element-type this[int index]
{
// The get accessor
...

set
{
// set the value specified by index
}
}

Use of Indexers
Declaration of behavior of an indexer is to some extent similar to a property
...
However,
properties return or set a specific data member, whereas indexers returns or sets a
particular value from the object instance
...

Defining a property involves providing a property name
...
The
following example demonstrates the concept:

259

using System;
namespace IndexerApplication
{
class IndexedNames
{
private string[] namelist = new string[size];
static public int size = 10;
public IndexedNames()
{
for (int i = 0; i < size; i++)
namelist[i] = "N
...
";
}
public string this[int index]
{
get
{
string tmp;

if( index >= 0 && index <= size-1 )
{
tmp = namelist[index];
}
else
{
tmp = "";
}

return ( tmp );
}

260

set
{
if( index >= 0 && index <= size-1 )
{
namelist[index] = value;
}
}
}

static void Main(string[] args)
{
IndexedNames names = new IndexedNames();
names[0] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";
names[4] = "Davinder";
names[5] = "Sunil";
names[6] = "Rubic";
for ( int i = 0; i < IndexedNames
...
WriteLine(names[i]);
}
Console
...
A
...
A
...
A
...
Indexers can also be declared with multiple parameters
and each parameter may be a different type
...
C# allows indexes to be of other types, for example, a string
...
A
...
size; i++)
{

264

Console
...
WriteLine(names["Nuha"]);
Console
...
A
...
A
...
A
...
DELEGATES
C# delegates are similar to pointers to functions, in C or C++
...
The reference can be
changed at runtime
...

All delegates are implicitly derived from the System
...


Declaring Delegates
Delegate declaration determines the methods that can be referenced by the delegate
...

For example, consider a delegate:
public delegate int MyDelegate (string s);

The preceding delegate can be used to reference any method that has a
single stringparameter and returns an int type variable
...
When creating a delegate, the
argument passed to the new expression is written similar to a method call, but
without the arguments to the method
...

printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);

Following example demonstrates declaration, instantiation, and use of a delegate that
can be used to reference methods that take an integer parameter and returns an
integer value
...
WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console
...
ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
Value of Num: 35
Value of Num: 175

Multicasting of a Delegate
Delegate objects can be composed using the "+" operator
...
Only delegates of the same type can be
composed
...

Using this property of delegates you can create an invocation list of methods that will
be called when a delegate is invoked
...
The
following program demonstrates multicasting of a delegate:
using System;

delegate int NumberChanger(int n);
namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)

268

{
num += p;
return num;
}

public static int MultNum(int q)
{
num *= q;
return num;
}
public static int getNum()
{
return num;
}

static void Main(string[] args)
{
//create delegate instances
NumberChanger nc;
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
nc = nc1;
nc += nc2;
//calling multicast
nc(5);
Console
...
ReadKey();
}
}

269

}

When the above code is compiled and executed, it produces the following result:
Value of Num: 75

Using Delegates
The following example demonstrates the use of delegate
...

We use this delegate to call two methods, the first prints the string to the console,
and the second one prints it to a file:
using System;
using System
...
WriteLine("The String is: {0}", str);
}
//this method prints to a file
public static void WriteToFile(string s)
{

270

fs = new FileStream("c:\\message
...
Append, FileAccess
...
WriteLine(s);
sw
...
Close();
fs
...
ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
The String is: Hello World

271

34
...
, or some
occurrence such as system generated notifications
...
For example, interrupts
...


Using Delegates with Events
The events are declared and raised in a class and associated with the event handlers
using delegates within the same class or some other class
...
This is called the publisher class
...
Events use
the publisher-subscriber model
...

The event-delegate association is also defined in this object
...

A subscriber is an object that accepts the event and provides an event handler
...


Declaring Events
To declare an event inside a class, first a delegate type for the event must be
declared
...


Example 1
using System;
namespace SimpleEvent

272

{
using System;

public class EventTest
{
private int value;

public delegate void NumManipulationHandler();

public event NumManipulationHandler ChangeNum;

protected virtual void OnNumChanged()
{
if (ChangeNum != null)
{
ChangeNum();
}
else
{
Console
...
SetValue(7);
e
...
ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
Event Fired!
Event Fired!
Event Fired!

Example 2
This example provides a simple application for troubleshooting for a hot water boiler
system
...

using System;
using System
...
K";
Boiler b = new Boiler(100, 12);
int t = b
...
getPressure();
if(t > 150 || t < 80 || p < 12 || p > 15)
{
remarks = "Need Maintenance";
}
OnBoilerEventLog("Logging Info:\n");
OnBoilerEventLog("Temparature " + t + "\nPressure: " + p);
OnBoilerEventLog("\nMessage: " + remarks);
}

protected void OnBoilerEventLog(string message)
{
if (BoilerEventLog != null)
{
BoilerEventLog(message);
}
}
}
// this class keeps a provision for writing into the log file
class BoilerInfoLogger
{

276

FileStream fs;
StreamWriter sw;
public BoilerInfoLogger(string filename)
{
fs = new FileStream(filename, FileMode
...
Write);
sw = new StreamWriter(fs);
}
public void Logger(string info)
{
sw
...
Close();
fs
...
WriteLine(info);
}//end of Logger

static void Main(string[] args)
{
BoilerInfoLogger filelog = new BoilerInfoLogger("e:\\boiler
...
BoilerEventLog += new
DelegateBoilerEvent
...
BoilerEventLog += new
DelegateBoilerEvent
...
Logger);
boilerEvent
...
ReadLine();
filelog
...
K

278

35
...
These classes
provide support for stacks, queues, lists, and hash tables
...

Collection classes serve various purposes, such as allocating memory dynamically to
elements and accessing a list of items on the basis of an index etc
...


Collection Classes and Their Usage
The
following
are
the
various
commonly
used
classes
of
the System
...
Click the following links to check their detail
...

It is basically an alternative to an array
...
It also
allows dynamic memory allocation, adding, searching and sorting
items in the list
...

A hash table is used when you need to access elements by using
key, and you can identify a useful key value
...
The key is used to access the
items in the collection
...

A sorted list is a combination of an array and a hash table
...
If you access items using an index, it is an ArrayList, and
if you access items using a key , it is a Hashtable
...


Stack

It represents a last-in, first out collection of object
...
When
you add an item in the list, it is called pushing the item and when
you remove it, it is called popping the item
...

It is used when you need a first-in, first-out access of items
...


BitArray

It represents an array of the binary representation using the
values 1 and 0
...
You can access items from the
BitArray collection by using an integer index, which starts from
zero
...
It is
basically an alternative to an array
...
It also allows dynamic memory allocation, adding, searching and
sorting items in the list
...


Count

Gets the number of elements actually contained in the
ArrayList
...


IsReadOnly

Gets a value indicating whether the ArrayList is read-only
...


The following table lists some of the commonly used methods of the ArrayList class:
Sr
...

1

Methods
public virtual int Add( object value );
Adds an object to the end of the ArrayList
...


3

public virtual void Clear();
Removes all elements from the ArrayList
...


5

public virtual ArrayList GetRange( int index, int count );
Returns an ArrayList which represents a subset of the elements in the
source ArrayList
...


7

public virtual void Insert( int index, object value );
Inserts an element into the ArrayList at the specified index
...


9

public virtual void Remove( object obj );
Removes the first occurrence of a specific object from the ArrayList
...


11

public virtual void RemoveRange( int index, int count );
Removes a range of elements from the ArrayList
...


13

public virtual void SetRange( int index, ICollection c );
Copies the elements of a collection over a range of elements in the
ArrayList
...


15

public virtual void TrimToSize();
Sets the capacity to the actual number of elements in the ArrayList
...
Collections;

namespace CollectionApplication
{
class Program
{
static void Main(string[] args)
{
ArrayList al = new ArrayList();

282

Console
...
Add(45);
al
...
Add(33);
al
...
Add(12);
al
...
Add(9);

Console
...
Capacity);
Console
...
Count);

Console
...
Write(i + " ");
}
Console
...
Write("Sorted Content: ");
al
...
Write(i + " ");
}
Console
...
ReadKey();
}
}

283

36
...

The Hashtable class represents a collection of key-and-value pairs that are
organized based on the hash code of the key
...

A hash table is used when you need to access elements by using key, and you can
identify a useful key value
...
The key
is used to access the items in the collection
...


IsFixedSize

Gets a value indicating whether the Hashtable has a fixed size
...


Item

Gets or sets the value associated with the specified key
...


Values

Gets an ICollection containing the values in the Hashtable
...
No
...


2

public virtual void Clear();

285

Removes all elements from the Hashtable
...


4

public virtual bool ContainsValue( object value );
Determines whether the Hashtable contains a specific value
...


Example
The following example demonstrates the concept:
using System;
using System
...
Add("001", "Zara Ali");
ht
...
Add("003", "Joe Holzner");
ht
...
Add("005", "M
...
Add("006", "M
...
Add("007", "Ritesh Saikia");

286

if (ht
...
WriteLine("This student name is already in the
list");
}
else
{
ht
...

ICollection key = ht
...
WriteLine(k + ": " + ht[k]);
}
Console
...
Amlan

287

006: M
...

A sorted list is a combination of an array and a hash table
...
If you access items using an index, it
is an ArrayList, and if you access items using a key, it is a Hashtable
...


Methods and Properties of the SortedList Class
The following table
the SortedList class:

lists

some

of

Property

the

commonly

used

properties

of

Description

Capacity

Gets or sets the capacity of the SortedList
...


IsFixedSize

Gets a value indicating whether the SortedList has a fixed
size
...


Item

Gets and sets the value associated with a specific key in the
SortedList
...


Values

Gets the values in the SortedList
...

No
...


2

public virtual void Clear();
Removes all elements from the SortedList
...


4

public virtual bool ContainsValue( object value );
Determines whether the SortedList contains a specific value
...


6

public virtual object GetKey( int index );
Gets the key at the specified index of the SortedList
...


8

public virtual IList GetValueList();
Gets the values in the SortedList
...


10

public virtual int IndexOfValue( object value );
Returns the zero-based index of the first occurrence of the specified
value in the SortedList
...

12

public virtual void RemoveAt( int index );
Removes the element at the specified index of SortedList
...


Example
The following example demonstrates the concept:
using System;
using System
...
Add("001", "Zara Ali");
sl
...
Add("003", "Joe Holzner");
sl
...
Add("005", "M
...
Add("006", "M
...
Add("007", "Ritesh Saikia");

290

if (sl
...
WriteLine("This student name is already in the
list");
}
else
{
sl
...

ICollection key = sl
...
WriteLine(k + ": " + sl[k]);
}
}
}
}
When the above code is compiled and executed, it produces the following result:
001: Zara Ali
002: Abida Rehman
003: Joe Holzner
004: Mausam Banazir Nur
005: M
...
Arif

291

007: Ritesh Saikia
008: Nuha Ali

Stack Class
It represents a last-in, first out collection of object
...
When you add an item in the list, it is called pushing the
item and when you remove it, it is called popping the item
...


The following table lists some of the commonly used methods of the Stack class:
Methods

Sr
...

1

public virtual void Clear();
Removes all elements from the Stack
...


3

public virtual object Peek();
Returns the object at the top of the Stack without removing it
...


5

public virtual void Push( object obj );
Inserts an object at the top of the Stack
...


Example
The following example demonstrates use of Stack:
using System;
using System
...
Push('A');
st
...
Push('G');
st
...
WriteLine("Current stack: ");
foreach (char c in st)
{
Console
...
WriteLine();

st
...
Push('H');

293

Console
...
Peek());
Console
...
Write(c + " ");
}
Console
...
WriteLine("Removing values ");
st
...
Pop();
st
...
WriteLine("Current stack: ");
foreach (char c in st)
{
Console
...
It is used when you need a firstin, first-out access of items
...


Methods and Properties of the Queue Class
The following table lists some of the commonly used properties of the Queue class:
Property
Count

Description
Gets the number of elements contained in the Queue
...
No
...


2

public virtual bool Contains( object obj );
Determines whether an element is in the Queue
...


4

public virtual void Enqueue( object obj );
Adds an object to the end of the Queue
...


6

public virtual void TrimToSize();

295

Sets the capacity to the actual number of elements in the Queue
...
Collections;

namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
Queue q = new Queue();

q
...
Enqueue('M');
q
...
Enqueue('W');

Console
...
Write(c + " ");
Console
...
Enqueue('V');
q
...
WriteLine("Current queue: ");
foreach (char c in q)
Console
...
WriteLine();
Console
...
Dequeue();
Console
...
Dequeue();
Console
...
ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
Current queue:
A M G W
Current queue:
A M G W V H
Removing values
The removed value: A
The removed value: M

BitArray Class
The BitArray class manages a compact array of bit values, which are represented as
Booleans, where true indicates that the bit is on (1) and false indicates the bit is off
(0)
...
You can access items from the BitArray collection by using an integer index,
which starts from zero
...


IsReadOnly

Gets a value indicating whether the BitArray is read-only
...


Length

Gets or sets the number of elements in the BitArray
...
No
...


2

public bool Get( int index );
Gets the value of the bit at a specific position in the BitArray
...


4

public BitArray Or( BitArray value );
Performs the bitwise OR operation on the elements in the current
BitArray against the corresponding elements in the specified BitArray
...


6

public void SetAll( bool value );
Sets all bits in the BitArray to the specified value
...


Example
The following example demonstrates the use of BitArray class:
using System;
using System
...
WriteLine("Bit array ba1: 60");
for (int i = 0; i < ba1
...
Write("{0, -6} ", ba1[i]);

299

}
Console
...
WriteLine("Bit array ba2: 13");
for (int i = 0; i < ba2
...
Write("{0, -6} ", ba2[i]);
}
Console
...
And(ba2);

//content of ba3
Console
...
Count; i++)
{
Console
...
WriteLine();

ba3 = ba1
...
WriteLine("Bit array ba3 after OR operation: 61");
for (int i = 0; i < ba3
...
Write("{0, -6} ", ba3[i]);

300

}
Console
...
ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
Bit array ba1: 60
False False True True True True False False
Bit array ba2: 13
True False True True False False False False
Bit array ba3 after AND operation: 12
False False True True False False False False
Bit array ba3 after OR operation: 61
True False True True False False False False

301

37
...
In other
words, generics allow you to write a class or method that can work with any data
type
...
When the compiler encounters a constructor for the class or a function
call for the method, it generates code to handle the specific data type
...
Collections
...
setItem(c, c*5);
}
//retrieving the values
for (int c = 0; c < 5; c++)
{
Console
...
getItem(c) + " ");
}
Console
...
setItem(c, (char)(c+97));
}
//retrieving the values
for (int c = 0; c< 5; c++)
{

303

Console
...
getItem(c) + " ");
}
Console
...
ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
0 5 10 15 20
a b c d e

Features of Generics
Generics is a technique that enriches your programs in the following ways:


It helps you to maximize code reuse, type safety, and performance
...
The
...
Collections
...
You may use these generic collection
classes instead of the collection classes in the System
...




You can create your own generic interfaces, classes, methods, events, and
delegates
...




You may get information on the types used in a generic data type at run-time
by means of reflection
...
The following program illustrates the concept:
using System;
using System
...
Generic;
namespace GenericMethodAppl
{

304

class Program
{
static void Swap(ref T lhs, ref T rhs)
{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
static void Main(string[] args)
{
int a, b;
char c, d;
a = 10;
b = 20;
c = 'I';
d = 'V';

//display values before swap:
Console
...
WriteLine("a = {0}, b = {1}", a, b);
Console
...
WriteLine("c = {0}, d = {1}", c, d);

//call swap
Swap(ref a, ref b);
Swap(ref c, ref d);

//display values after swap:

305

Console
...
WriteLine("a = {0}, b = {1}", a, b);
Console
...
WriteLine("c = {0}, d = {1}", c, d);
Console
...
For example:
delegate T NumberChanger(T n);

The following example shows use of this delegate:
using System;
using System
...
Generic;

delegate T NumberChanger(T n);
namespace GenericDelegateAppl
{

306

class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
}

public static int MultNum(int q)
{
num *= q;
return num;
}
public static int getNum()
{
return num;
}

static void Main(string[] args)
{
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
//calling the methods using the delegate objects
nc1(25);
Console
...
WriteLine("Value of Num: {0}", getNum());

307

Console
...
ANONYMOUS METHODS
We discussed that delegates are used to reference any methods that has the same
signature as that of the delegate
...

Anonymous methods provide a technique to pass a code block as a delegate
parameter
...

You need not specify the return type in an anonymous method; it is inferred from the
return statement inside the method body
...
For example,
delegate void NumberChanger(int n);

...
WriteLine("Anonymous Method: {0}", x);
};

The code block Console
...

The delegate could be called both with anonymous methods as well as named
methods in the same way, i
...
, by passing the method parameters to the delegate
object
...
WriteLine("Named Method: {0}", num);
}

public static void MultNum(int q)
{
num *= q;
Console
...
WriteLine("Anonymous Method: {0}", x);
};

310

//calling the delegate using the anonymous method
nc(10);

//instantiating the delegate using the named methods
nc =

new NumberChanger(AddNum);

//calling the delegate using the named methods
nc(5);

//instantiating the delegate using another named methods
nc =

new NumberChanger(MultNum);

//calling the delegate using the named methods
nc(2);
Console
...
UNSAFE CODES
C# allows using pointer variables in a function of code block when it is marked by
the unsafe modifier
...


Pointers
A pointer is a variable whose value is the address of another variable i
...
, the direct
address of the memory location
...

The general form of a pointer declaration is:
type *var-name;

Following are valid pointer declarations:
int

*ip;

/* pointer to an integer */

double *dp;

/* pointer to a double */

float

*fp;

/* pointer to a float */

char

*ch

/* pointer to a character */

The following example illustrates use of pointers in C#, using the unsafe modifier:
using System;
namespace UnsafeCodeApplication
{
class Program
{
static unsafe void Main(string[] args)
{
int var = 20;
int* p = &var;
Console
...
WriteLine("Address is: {0}",

(int)p);

Console
...
The example in the following section shows this
...
The following example demonstrates this:
using System;
namespace UnsafeCodeApplication
{
class Program
{
public static void Main()
{
unsafe
{
int var = 20;
int* p = &var;
Console
...
WriteLine("Data is: {0} " , p->ToString());
Console
...
ReadKey();
}
}
}

When the above code was compiled and executed, it produces the following result:
Data is: 20
Data is: 20
Address is: 77128984

Passing Pointers as Parameters to Methods
You can pass a pointer variable to a method as parameter
...
WriteLine("Before Swap: var1:{0}, var2: {1}", var1, var2);
p
...
WriteLine("After Swap: var1:{0}, var2: {1}", var1, var2);
Console
...
For example, int *p and int[] p, are not same type
...

Therefore, if you need to access an array data using a pointer variable, as we
traditionally do in C, or C++ ( please check: C Pointers), you need to fix the pointer
using the fixed keyword
...
WriteLine("Address of list[{0}]={1}",i,(int)(ptr + i));
Console
...
ReadKey();
}
}
}

When the above code was compiled and executed, it produces the following result:
Address of list[0] = 31627168
Value of list[0] = 10
Address of list[1] = 31627172
Value of list[1] = 100
Address of list[2] = 31627176
Value of list[2] = 200

Compiling Unsafe Code
For compiling unsafe code, you have to specify the /unsafe command-line switch
with command-line compiler
...
cs containing unsafe code, from
command line, give the command:
csc /unsafe prog1
...

To do this:


Open project properties by double clicking the properties node in the
Solution Explorer
...




Select the option "Allow unsafe code"
...
MULTITHREADING
A thread is defined as the execution path of a program
...
If your application involves complicated and time consuming
operations, then it is often helpful to set different execution paths or threads, with
each thread performing a particular job
...
One common example of use of thread is
implementation of concurrent programming by modern operating systems
...

So far we wrote the programs where a single thread runs as a single process which
is the running instance of the application
...
To make it execute more than one task at a time, it could
be divided into smaller threads
...
Threading
...

Following are the various states in the life cycle of a thread:


The Unstarted State: It is the situation when the instance of the thread is
created but the Start method is not called
...




The Not Runnable State: A thread is not executable, when:
o
o

Wait method has been called

o


Sleep method has been called
Blocked by I/O operations

The Dead State: It is the situation when the thread completes execution or
is aborted
...
Threading
...
It allows
creating and accessing individual threads in a multithreaded application
...

When a C# program starts execution, the main thread is automatically created
...
You can access a thread using the CurrentThread property of the Thread
class
...
Threading;

namespace MultithreadingApplication
{
class MainThreadProgram
{
static void Main(string[] args)
{
Thread th = Thread
...
Name = "MainThread";
Console
...
Name);
Console
...


CurrentCulture

Gets or sets the culture for the current thread
...


CurrentThread

Gets the currently running thread
...


ExecutionContext

Gets an ExecutionContext object that contains information
about the various contexts of the current thread
...


IsBackground

Gets or sets a value indicating whether or not a thread is a
background thread
...


ManagedThreadId

Gets a unique identifier for the current managed thread
...


Priority

Gets or sets a value indicating the scheduling priority of a
thread
...


The following table shows some of the most commonly used methods of
the Thread class:
Methods

Sr
...

1

public void Abort()
Raises a ThreadAbortException in the thread on which it is invoked, to
begin the process of terminating the thread
...


320

2

public static LocalDataStoreSlot AllocateDataSlot()
Allocates an unnamed data slot on all the threads
...


3

public static LocalDataStoreSlot AllocateNamedDataSlot( string
name)
Allocates a named data slot on all threads
...


4

public static void BeginCriticalRegion()
Notifies a host that execution is about to enter a region of code in which
the effects of a thread abort or unhandled exception might jeopardize other
tasks in the application domain
...


6

public static void EndCriticalRegion()
Notifies a host that execution is about to enter a region of code in which
the effects of a thread abort or unhandled exception are limited to the
current task
...


8

public static void FreeNamedDataSlot(string name)
Eliminates the association between a name and a slot, for all threads in the
process
...


9

public static Object GetData( LocalDataStoreSlot slot )
Retrieves the value from the specified slot on the current thread, within
the current thread's current domain
...


10

public static AppDomain GetDomain()

321

Returns the current domain in which the current thread is running
...
For better performance, use fields that are
marked with the ThreadStaticAttribute attribute instead
...


14

public void Join()
Blocks the calling thread until a thread terminates, while continuing to
perform standard COM and SendMessage pumping
...


15

public static void MemoryBarrier()
Synchronizes memory access as follows: The processor executing the
current thread cannot reorder instructions in such a way that memory
accesses prior to the call to MemoryBarrier execute after memory accesses
that follow the call to MemoryBarrier
...


17

public static void SetData( LocalDataStoreSlot slot, Object data )
Sets the data in the specified slot on the currently running thread, for that
thread's current domain
...


18

public void Start()
Starts a thread
...


322

20

public static void SpinWait( int iterations )
Causes a thread to wait the number of times defined by the iterations
parameter

21

public
static
byte
VolatileRead(
ref
byte
address
)
public static double VolatileRead( ref double address )
public
static
int
VolatileRead(
ref
int
address
)
public static Object VolatileRead( ref Object address )
Reads the value of a field
...
This method has different overloaded forms
...


22

public
public
public
public

static void VolatileWrite( ref byte address, byte value )
static void VolatileWrite( ref double address, double value )
static void VolatileWrite( ref int address, int value )
static void VolatileWrite( ref Object address, Object value )

Writes a value to a field immediately, so that the value is visible to all
processors in the computer
...

Only some are given above
...
The operating system selects the thread
to yield to
...
The extended Thread class then
calls the Start() method to begin the child thread execution
...
Threading;

namespace MultithreadingApplication
{
class ThreadCreationProgram

323

{
public static void CallToChildThread()
{
Console
...
WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread
...
ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
In Main: Creating the Child thread
Child thread starts

Managing Threads
The Thread class provides various methods for managing threads
...

using System;
using System
...
WriteLine("Child thread starts");
// the thread is paused for 5000 milliseconds
int sleepfor = 5000;
Console
...
Sleep(sleepfor);
Console
...
WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread
...
ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
In Main: Creating the Child thread
Child thread starts
Child Thread Paused for 5 seconds
Child thread resumes

325

Destroying Threads
The Abort() method is used for destroying threads
...
This exception
cannot be caught, the control is sent to the finally block, if any
...
Threading;

namespace MultithreadingApplication
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
try
{

Console
...
Sleep(500);
Console
...
WriteLine("Child Thread Completed");

}
catch (ThreadAbortException e)
{

326

Console
...
WriteLine("Couldn't catch the Thread Exception");
}

}

static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console
...
Start();
//stop the main thread for some time
Thread
...
WriteLine("In Main: Aborting the Child thread");
childThread
...
ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:
In Main: Creating the Child thread
Child thread starts
0

327

1
2
In Main: Aborting the Child thread
Thread Abort Exception
Couldn't catch the Thread Exception

328


Title: C# notes
Description: notes