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: it is given C# notes with best descibe which you can understand easily.

Document Preview

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


C# Tutorial

C# TUTORIAL

Simply Easy Learning by tutorialspoint
...
com
i

ABOUT THE TUTORIAL

C# Tutorial
C# is a simple, modern, general-purpose, object-oriented programming language developed by Microsoft
within its
...

This tutorial will teach you basic C# programming and will also take you through various advanced concepts
related to C# programming language
...
After
completing this tutorial, you will find yourself at a moderate level of expertise in C# programming from
where you can take yourself to next levels
...


Copyright & Disclaimer Notice
All

the content and graphics on this tutorial are the property of tutorialspoint
...
Any content from
tutorialspoint
...
com
...

This tutorial may contain inaccuracies or errors and tutorialspoint provides no guarantee regarding the
accuracy of the site or its contents including this tutorial
...
com site or
this tutorial content contains some errors, please contact us at webmaster@tutorialspoint
...
2
Audience
...
2
Copyright & Disclaimer Notice
...
11
Strong Programming Features of C#
...
13
The
...
13
Integrated Development Environment (IDE) For C#
...
14

C# Program Structure
...
15
Compile & Execute a C# Program:
...
18
The using Keyword
...
19
Comments in C#
...
19
Member Functions
...
19
Identifiers
...
20

C# Data Types
...
22
Reference Types
...
23
DYNAMIC TYPE
...
24
Pointer Types
...
25
C# Type Conversion Methods
...
28
Variable Declaration in C#
...
29
Accepting Values from User
...
30

C# Constants and Literals
...
31
Floating-point Literals
...
32
String Literals
...
33

C# Operators
...
34
Example
...
35
Example
...
37
Example
...
38
Example
...
40
Example
...
42
Example
...
43
Example
...
45
If statement
...
46
Flow Diagram:
...
46
If…else statement
...
47
Example:
...
else if
...
49
Syntax:
...
49
nested if statements
...
50
Example:
...
51
Syntax:
...
52
Example:
...
53
TUTORIALS POINT
Simply Easy Learning

Syntax:
...
53
The ? : Operator:
...
55
while loop
...
56
Flow Diagram:
...
57
for loop
...
57
Flow Diagram:
...
58
do…while loop
...
59
Flow Diagram:
...
60
nested loops
...
61
Example:
...
62
break statement
...
63
Flow Diagram:
...
63
continue statement
...
64
Flow Diagram:
...
65
The Infinite Loop:
...
67
Public Access Specifier
...
68
Protected Access Specifier
...
69
Protected Internal Access Specifier
...
71
Defining Methods in C#
...
71
Calling Methods in C#
...
73
Passing Parameters to a Method
...
74
Reference parameters
...
77

C# Nullables
...
80

C# Arrays
...
81
Initializing an Array
...
82
Accessing Array Elements
...
83
C# Arrays in Detail
...
85
Accessing Two-Dimensional Array Elements
...
89
Example
...
92
Creating a String Object
...
93
Methods of the String Class
...
95
Comparing Strings:
...
98
Defining a Structure
...
99
Class vs Structure
...
102
Declaring enum Variable
...
102

C# Classes
...
104
Member Functions and Encapsulation
...
107
Destructors in C#
...
109

C# Inheritance
...
111
TUTORIALS POINT
Simply Easy Learning

Base Class Initialization
...
113

C# Polymorphism
...
115
Function Overloading
...
116

C# Operator Overloading
...
119
Overloadable and Non-Overloadable Operators
...
121

C# Interfaces
...
125
Example
...
127
Defining a Namespace
...
128
Nested Namespaces
...
131
List of Preprocessor Directives in C#
...
132
Conditional Directives
...
134
Constructs for Defining Regular Expressions
...
134
Character classes
...
136
Grouping constructs
...
137
Backreference constructs
...
138
Substitution
...
139
The Regex Class
...
140
Example 2
...
141

C# Exception Handling
...
142
Exception Classes in C#
...
143
Creating User-Defined Exceptions
...
145

C# File I/O
...
146
The FileStream Class
...
147
Advanced File Operations in C#
...
148
Example:
...
150
Example:
...
151
The BinaryWriter Class
...
152
The DirectoryInfo Class
...
155
Example
...
157
Specifying an Attribute
...
157
AttributeUsage:
...
158
Obsolete
...
160
Declaring a Custom Attribute
...
160
Applying the Custom Attribute
...
163
Uses of Reflection
...
163
Example
...
168
Accessors
...
169
Abstract Properties
...
173
Syntax
...
173
TUTORIALS POINT
Simply Easy Learning

Overloaded Indexers
...
177
Declaring Delegates
...
177
Multicasting of a Delegate
...
179

C# Events
...
181
Declaring Events
...
181
Example 2:
...
185
Various Collection Classes and Their Usage
...
186
Example:
...
188
Methods and Properties of the SortedList Class
...
191
Methods and Properties of the Stack Class
...
192
Methods and Properties of the Queue Class
...
194
Example:
...
198
Features of Generics
...
199
Generic Delegates
...
202
Syntax for Writing an Anonymous Method
...
202

C# Unsafe Codes
...
204
Retrieving the Data Value Using a Pointer
...
206
Accessing Array Elements Using a Pointer
...
208

C# Multithreading
...
209
The Main Thread
...
210
Creating Threads
...
213
Destroying Threads
...

C# was developed by Anders Hejlsberg and his team during the development of
...

C# is designed for Common Language Infrastructure (CLI), which consists of the executable code and runtime
environment that allows use of various high-level languages to be used on different computer platforms and
architectures
...




Component oriented
...




Structured language
...




It can be compiled on a variety of computer platforms
...
Net Framework
...

Following is the list of few important features:



Boolean Conditions

TUTORIALS POINT
Simply Easy Learning



Automatic Garbage Collection



Standard Library



Assembly Versioning



Properties and Events



Delegates and Events Management



Easy-to-use Generics



Indexers



Conditional Compilation



Simple Multithreading



LINQ and Lambda Expressions



Integration with Windows

TUTORIALS POINT
Simply Easy Learning

2

CHAPTER

C# Environment

I

n this chapter, we will discuss the tools required for creating C# programming
...
Net framework and is used for writing
...
Therefore, before discussing the available tools
for running a C# program, let us understand how C# relates to the
...


The
...
Net framework is a revolutionary platform that helps you to write the following types of applications:



Windows applications



Web applications



Web services

The
...
The framework has been designed in such a way
that it can be used from any of the following languages: C#, C++, Visual Basic, Jscript, COBOL, etc
...

The
...
Following are
some of the components of the
...
Net Framework Class Library



Common Language Specification



Common Type System



Metadata and Assemblies



Windows Forms



ASP
...
Net AJAX



ADO
...
Net - Introduction, and for details of each
component, please consult Microsoft's documentation
...
Using these tools, you can write all kinds of C#
programs from simple command-line applications to more complex applications
...
NET Framework
...
They retain most features of Visual Studio
...

You can download it from Microsoft Visual Studio
...
Please note that
you need an active internet connection for installing the express edition
...
NET Framework runs on the Windows operating system, there are some alternative versions that work
on other operating systems
...
NET Framework which includes a C# compiler
and runs on several operating systems, including various flavors of Linux and Mac OS
...

The stated purpose of Mono is not only to be able to run Microsoft
...
Mono can be run on many operating systems including Android, BSD,
iOS, Linux, OS X, Windows, Solaris and UNIX
...


C# Hello World Example
A C# program basically consists of the following parts:



Namespace declaration



A class



Class methods



Class attributes



A Main method



Statements & Expressions



Comments

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

TUTORIALS POINT
Simply Easy Learning

When the above code is compiled and executed, it produces the following result:
Hello World
Let us look at various parts of the above 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 would contain more than one method
...

However, the HelloWorld class has only one method Main
...
The Main method states
what the class will do when executed
The next line /*
...

The Main method specifies its behavior with the statement Console
...
This statement causes the
message "Hello, World!" to be displayed on the screen
...
ReadKey(); is for the VS
...
This makes the program wait for a key press and it
prevents the screen from running and closing quickly when the program is launched from Visual Studio
...


It's worth to note the following points:



C# is case sensitive
...




The program execution starts at the Main method
...


Compile & Execute a C# Program:
If you are using Visual Studio
...




On the menu bar, choose File, New, Project
...




Choose Console Application
...




The new project appears in Solution Explorer
...




Click the Run button or the F5 key to run the project
...


TUTORIALS POINT
Simply Easy Learning

You can compile a C# program by using the command-line instead of the Visual Studio IDE:



Open a text editor and add the above-mentioned code
...
cs



Open the command prompt tool and go to the directory where you saved the file
...
cs and press enter to compile your code
...
exe executable file
...




You will be able to see "Hello World" printed on the screen
...
In Object-Oriented Programming methodology, a program

consists of various objects that interact with each other by means of actions
...
Objects of the same kind are said to have the same type or, more often, are said to be in the same
class
...
It has attributes like length and width
...

Let us look at an implementation of a Rectangle class and discuss C# basic syntax, on the basis of our observations
in it:
using System;
namespace RectangleApplication
{
class Rectangle
{
// member variables
double length;
double width;
public void Acceptdetails()
{
length = 4
...
5;
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console
...
WriteLine("Width: {0}", width);
Console
...
Acceptdetails();
r
...
ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Length: 4
...
5
Area: 15
...
A program can include multiple using
statements
...


Comments in C#
Comments are used for explaining code
...
The multiline comments in C#
programs start with /* and terminates with the characters */ as shown below:
/* This program demonstrates
The basic syntax of C# programming
Language */
Single-line comments are indicated by the '//' symbol
...
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
...

In C#, some identifiers have special meaning in context of code, such as get and set, these are called contextual
keywords
...
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 floating point type

(+/-)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 to
9,223,372,036,854,775,807

0L

sbyte

8-bit signed integer type

-128 to 127

0

TUTORIALS POINT
Simply Easy Learning

short

16-bit signed integer type

-32,768 to 32,767

0

uint

32-bit unsigned integer type

0 to 4,294,967,295

0

ulong

64-bit unsigned integer type

0 to 18,446,744,073,709,551,615

0

ushort

16-bit unsigned integer type

0 to 65,535

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 Types
The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables
...
Using more than one variable, the reference types can refer to a
memory location
...
Example of built-in reference types are: object, dynamic and string
...
Object is an alias
for System
...
So object types can be assigned values of any other types, value types, reference types,
predefined or user-defined 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 runtime
...


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 in C
or C++
...


TUTORIALS POINT
Simply Easy Learning

6

CHAPTER

C# Type Conversion

T

ype conversion is basically type casting or converting one type of data to another type
...
Examples are
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
...
N

Methods & Description

TUTORIALS POINT
Simply Easy Learning

1

ToBoolean
Converts a type to a Boolean value, where possible
...


3

ToChar
Converts a type to a single Unicode character, where possible
...


5

ToDecimal
Converts a floating point or integer type to a decimal type
...


7

ToInt16
Converts a type to a 16-bit integer
...


9

ToInt64
Converts a type to a 64-bit integer
...


11

ToSingle
Converts a type to a small floating point number
...


13

ToType
Converts a type to a specified type
...


15

ToUInt32
Converts a type to an unsigned long type
...


The following example converts various value types to string type:
namespace TypeConversionApplication
{
class StringConversion
{
static void Main(string[] args)
{
int i = 75;
float f = 53
...
7652;

TUTORIALS POINT
Simply Easy Learning

bool b = true;
Console
...
ToString());
Console
...
ToString());
Console
...
ToString());
Console
...
ToString());
Console
...
005
2345
...
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
...
The basic value types provided in C# can be categorized as:
Type

Example

Integral types

sbyte, byte, short, ushort, int, uint, long, ulong and char

Floating point types

float and double

Decimal types

decimal

Boolean types

true or false values, as assigned

Nullable types

Nullable data types

C# also allows defining other value types of variable like enum and reference types of variables like class, which we
will cover in subsequent chapters
...


Variable Definition in C#
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, etc
...

Some valid variable definitions are shown here:
int i, j, k;
char c, ch;
float f, salary;
double d;
You can initialize a variable at the time of definition as:

TUTORIALS POINT
Simply Easy Learning

int i = 100;

Variable Initialization in C#
Variables are initialized (assigned a value) with an equal sign followed by a constant expression
...
The initializer consists of an equal sign
followed by a constant expression as:
= value;
Some examples are:
int d = 3, f = 5;
byte z = 22;
double pi = 3
...
*/
initializes z
...
*/
the variable x has the value 'x'
...

Try the following example, which makes use of various types of variables:
namespace VariableDefinition
{
class Program
{
static void Main(string[] args)
{
short a;
int b ;
double c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
Console
...
ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
a = 10, b = 20, c = 30

Accepting Values from User
The Console class in the System namespace provides a function ReadLine() for accepting input from the user and
store it into a variable
...
ToInt32(Console
...
ToInt32() converts the data entered by the user to int data type, because
Console
...


Lvalues and Rvalues in C#:
There are two kinds of expressions in C#:
1
...


2
...


Variables are lvalues and so may appear on the left-hand side of an assignment
...
Following is a valid statement:
int g = 20;
But following is not a valid statement and would generate compile-time error:
10 = 20;

TUTORIALS POINT
Simply Easy Learning

8

CHAPTER

C# Constants and Literals

T

he 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 is required for decimal numbers
...
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
314159E-5L
510E
210f

...
The signed
exponent is introduced by e or E
...
g
...
A character
literal can be a plain character (e
...
, 'x'), an escape sequence (e
...
, '\t'), or a universal character (e
...
, '\u02C0')
...
Here, you have 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

\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,
"hello,
dear"
"hello,
@"hello

dear"
\
" "d" "ear"
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

TUTORIALS POINT
Simply Easy Learning

9

CHAPTER

C# Operators

A

n operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations
...


Arithmetic Operators
Following table shows all the arithmetic operators supported by C#
...
WriteLine("Line
c = a - b;
Console
...
WriteLine("Line
c = a / b;
Console
...
WriteLine("Line
c = a++;
Console
...
WriteLine("Line
Console
...
Assume variable A holds 10 and variable B holds
20, then:
Operator Description

Example

==

Checks if the values of two operands are equal or not, if yes then condition becomes
true
...


!=

Checks if the values of two operands are equal or not, if values are not equal then
condition becomes true
...


TUTORIALS POINT
Simply Easy Learning

>

Checks if the value of left operand is greater than the value of right operand, if yes
then condition becomes true
...


<

Checks if the value of left operand is less than the value of right operand, if yes then
condition becomes true
...


>=

Checks if the value of left operand is greater than or equal to the value of right
operand, if yes then condition becomes true
...


<=

Checks if the value of left operand is less than or equal to the value of right operand,
if yes then condition becomes true
...


Example
Try the following example to understand all the relational operators available in C#:
using System;
class Program
{
static void Main(string[] args)
{
int a = 21;
int b = 10;
if (a == b)
{
Console
...
WriteLine("Line 1 - a is not equal to b");
}
if (a < b)
{
Console
...
WriteLine("Line 2 - a is not less than b");
}
if (a > b)
{
Console
...
WriteLine("Line 3 - a is not greater than b");
}
/* Lets change value of a and b */
a = 5;
b = 20;
if (a <= b)
{
Console
...
WriteLine("Line 5-b is either greater than or equal to b");
}
}

TUTORIALS POINT
Simply Easy Learning

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

1
2
3
4
5

-

a
a
a
a
b

is
is
is
is
is

not equal to b
not less than b
greater than b
either less than or equal to b
either greater than or equal to b

Logical Operators
Following table shows all the logical operators supported by C#
...
If both the operands are non zero then condition
becomes true
...


||

Called Logical OR Operator
...


(A || B) is true
...
Use to reverses the logical state of its operand
...


!(A && B) is
true
...
WriteLine("Line 1 - Condition is true");
}
if (a || b)
{
Console
...
WriteLine("Line 3 - Condition is true");
}
else
{
Console
...
WriteLine("Line 4 - Condition is true");
}
Console
...
The truth tables for &, |, and ^ are as follows:
P

Q

p&q

p|q

p^q

0

0

0

0

0

0

1

0

1

1

1

1

1

1

0

1

0

0

1

1

Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
----------------A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C# are listed in the following table
...


TUTORIALS POINT
Simply Easy Learning

|

Binary OR Operator copies a bit if it exists in either operand
...


(A ^ B) will give
49, which is
0011 0001

~

Binary Ones Complement Operator is unary and has the effect of 'flipping' bits
...
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

TUTORIALS POINT
Simply Easy Learning

Line
Line
Line
Line
Line

2
3
4
5
6

-

Value
Value
Value
Value
Value

of
of
of
of
of

c
c
c
c
c

is
is
is
is
is

61
49
-61
240
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 will
assign 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

^=

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
Try the following example to understand all the assignment operators available in C#:
using System;
namespace OperatorsAppl
{
class Program
{

TUTORIALS POINT
Simply Easy Learning

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);

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 - ^=
c |= 2;
Console
...
ReadLine();

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

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

1 - =
2 - +=
3 - -=
4 - *=
5 - /=
6 - %=
7 - <<=
8 - >>=
9 - &=
10 - ^=
11 - |=

Value
Value
Value
Value
Value
Value
Value
Value
Value
Value
Value

TUTORIALS POINT
Simply Easy Learning

of
of
of
of
of
of
of
of
of
of
of

c
c
c
c
c
c
c
c
c
c
c

=
=
=
=
=
=
=
=
=
=
=

21
42
21
441
21
11
44
11
2
0
2

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


sizeof(int), will return 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
...


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);
Console
...
This affects how an expression is evaluated
...

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom
...

Category

Operator

Associativity

Postfix

() [] ->
...
WriteLine("Value of (a + b) * c / d is : {0}", e);
e = ((a + b) * c) / d;
// (30 * 15 ) / 5
Console
...
WriteLine("Value of (a + b) * (c / d) is

: {0}", e);

e = a + (b * c) / d;
// 20 + (150/5)
Console
...
ReadLine();

: {0}", e);

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

of
of
of
of

(a + b) * c / d is : 90
((a + b) * c) / d is : 90
(a + b) * (c / d) is : 90
a + (b * c) / d is : 50

TUTORIALS POINT
Simply Easy Learning

CHAPTER

10
C# Decision Making

D

ecision making structures require that the programmer 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
...


TUTORIALS POINT
Simply Easy Learning

nested if 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 swicth 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 will be executed
...


Flow Diagram:

Example:
using System;
namespace DecisionMaking
{

TUTORIALS POINT
Simply Easy Learning

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


Syntax:
The syntax of an if
...


Flow Diagram:

TUTORIALS POINT
Simply Easy Learning

Example:
using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
/* local variable definition */
int a = 100;
/* check the boolean condition */
if (a < 20)
{
/* if condition is true then print the following */
Console
...
WriteLine("a is not less than 20");
}
Console
...
ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
a is not less than 20;
value of a is : 100

TUTORIALS POINT
Simply Easy Learning

The if
...
else Statement
An if statement can be followed by an optional else if
...
else if statement
...




An if can have zero or one else's and it must come after any else if's
...




Once an else if succeeds, none of the remaining else if's or else's will be tested
...
else if
...
WriteLine("Value of a is 10");
}
else if (a == 20)
{
/* if else if condition is true */

TUTORIALS POINT
Simply Easy Learning

Console
...
WriteLine("Value of a is 30");
}
else
{
/* if none of the conditions is true */
Console
...
WriteLine("Exact value of a is: {0}", a);
Console
...


Syntax:
The syntax for a nested if statement is as follows:
if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
}
You can nest else if
...


Example:
using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
//* local variable definition */
int a = 100;
int b = 200;

TUTORIALS POINT
Simply Easy Learning

/* check the boolean condition */
if (a == 100)
{
/* if condition is true then check the following */
if (b == 200)
{
/* if condition is true then print the following */
Console
...
WriteLine("Exact value of a is : {0}", a);
Console
...
ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200

switch statement
A switch statement allows a variable to be tested for equality against a list of values
...


Syntax:
The syntax for a switch statement in C# is as follows:
switch(expression){
case constant-expression
statement(s);
break; /* optional */
case constant-expression
statement(s);
break; /* optional */

:
:

/* you can have any number of case statements */
default : /* Optional */
statement(s);
}
The following rules apply to a switch statement:



The expression used in a switch statement must have an integral or enumerated type, or be of a class type in
which the class has a single conversion function to an integral or enumerated type
...
Each case is followed by the value to be compared
to and a colon
...




When the variable being switched on is equal to a case, the statements following that case will execute until
a break statement is reached
...




Not every case needs to contain a break
...




A switch statement can have an optional default case, which must appear at the end of the switch
...
No break is needed in the default case
...
WriteLine("Excellent!");
break;

TUTORIALS POINT
Simply Easy Learning

case 'B':
case 'C':
Console
...
WriteLine("You passed");
break;
case 'F':
Console
...
WriteLine("Invalid grade");
break;
}
Console
...
ReadLine();

{0}", grade);

}
}
}
When the above code is compiled and executed, it produces the following result:
Well done
Your grade is B

nested switch statement
It is possible to have a switch as part of the statement sequence of an outer switch
...


Syntax:
The syntax for a nested switch statement is as follows:
switch(ch1)
{
case 'A':
printf("This A is part of outer switch" );
switch(ch2)
{
case 'A':
printf("This A is part of inner switch" );
break;
case 'B': /* inner B case code */
}
break;
case 'B': /* outer B case code */

}

Example:
using System;
namespace DecisionMaking
{
class Program
{

TUTORIALS POINT
Simply Easy Learning

static void Main(string[] args)
{
int a = 100;
int b = 200;
switch (a)
{
case 100:
Console
...
WriteLine("This is part of inner switch ");
break;
}
break;
}
Console
...
WriteLine("Exact value of b is : {0}", b);
Console
...
elsestatements
...
Notice the use and placement of the colon
...
If it is true, then Exp2 is evaluated and becomes
the value of the entire ? expression
...


TUTORIALS POINT
Simply Easy Learning

CHAPTER

11
C# Loops

T

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


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


Flow Diagram:

TUTORIALS POINT
Simply Easy Learning

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;
/* while loop execution */
while (a < 20)
{
Console
...
ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
value
value
value
value
value
value
value
value
value
value

of
of
of
of
of
of
of
of
of
of

a:
a:
a:
a:
a:
a:
a:
a:
a:
a:

10
11
12
13
14
15
16
17
18
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 checks its condition
at the bottom of the loop
...
while loop is similar to a while loop, except that a do
...


Syntax:
The syntax of a do
...

If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again
...


TUTORIALS POINT
Simply Easy Learning

Flow Diagram:

Example:
using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
/* local variable definition */
int a = 10;
/* do loop execution */
do
{
Console
...
ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
value
value
value
value
value
value

of
of
of
of
of
of

a:
a:
a:
a:
a:
a:

10
11
12
13
14
15

TUTORIALS POINT
Simply Easy Learning

value
value
value
value

of
of
of
of

a:
a:
a:
a:

16
17
18
19

nested loops
C# allows to use one loop inside another loop
...


Syntax:
The syntax for a nested for loop statement in C# is as follows:
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}
The syntax for a nested while loop statement in C# is as follows:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
The syntax for a nested do
...
For example a for
loop can be inside a while loop or vice versa
...
WriteLine("{0} is prime", i);
}
Console
...
When execution leaves a scope, all automatic
objects that were created in that scope are destroyed
...
Click the following links to check their details
...


TUTORIALS POINT
Simply Easy Learning

continue statement

Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating
...
When the break statement is encountered inside a loop, the loop is immediately terminated and program control
resumes at the next statement following the loop
...
It can be used to terminate a case in the switch statement
...
e
...


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

Flow Diagram:

Example:
using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
/* local variable definition */
int a = 10;

TUTORIALS POINT
Simply Easy Learning

/* while loop execution */
while (a < 20)
{
Console
...
ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
value
value
value
value
value
value

of
of
of
of
of
of

a:
a:
a:
a:
a:
a:

10
11
12
13
14
15

continue statement
The continue statement in C# works somewhat like the break statement
...

For the for loop, continue statement causes the conditional test and increment portions of the loop to execute
...
while loops, continue statement causes the program control passes to the conditional tests
...
WriteLine("value of a: {0}", a);
a++;
} while (a < 20);
Console
...
The for loop is traditionally used for this purpose
...

using System;
namespace Loops
{
class Program
{
static void Main(string[] args)
{
for (; ; )
{
Console
...
You may have an initialization and increment
expression, but programmers more commonly use the for(;;) construct to signify an infinite loop
...


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() and Display() 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;

TUTORIALS POINT
Simply Easy Learning

double GetArea()
{
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
...


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


TUTORIALS POINT
Simply Easy Learning

CHAPTER

13
C# Methods

A

method is a group of statements that together perform a task
...

To use a method, you need to:



Define the method



Call the method

Defining Methods in C#
When you define a method, you basically declare the elements of its structure
...

Return type: A method may return a value
...
If
the method is not returning any values, then the return type is void
...
It cannot be same as any other
identifier declared in the class
...
The parameter list refers to the type, order, and number of the parameters of a method
...

Method body: This contains the set of instructions needed to complete the required activity
...
It
has public access specifier, so it can be accessed from outside the class using an instance of the class
...

}

Calling Methods in C#
You can call a method using the name of the method
...
FindMax(a, b);
Console
...
ReadLine();
}
}
When the above code is compiled and executed, it produces the following result:
Max value is : 200
You can also call public method from other classes by using the instance of the class
...

using System;

TUTORIALS POINT
Simply Easy Learning

namespace CalculatorApplication
{
class NumberManipulator
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
}
class Test
{
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
...
This is known as recursion
...
WriteLine("Factorial of 6 is : {0}", n
...
WriteLine("Factorial of 7 is : {0}", n
...
WriteLine("Factorial of 8 is : {0}", n
...
ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320

Passing Parameters to a Method
When method with parameters is called, you need to pass the parameters to the method
...
In this case, changes made to the parameter inside the function have
no effect on the argument
...
This means that changes made to the parameter affect the
argument
...


Value parameters
This is the default mechanism for passing parameters to a method
...

The values of the actual parameters are copied into them
...
The following example demonstrates the concept:
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public void swap(int x, int y)

TUTORIALS POINT
Simply Easy Learning

{
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);
/* 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 :100
After swap, value of b :200
It shows that there is no change in the values though they had been changed inside the function
...
When you pass parameters by reference,
unlike value parameters, a new storage location is not created for these parameters
...

In C#, you declare the reference parameters using the ref keyword
...
WriteLine("Before swap, value of a : {0}", a);
Console
...
swap(ref a, ref b);

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

Console
...


TUTORIALS POINT
Simply Easy Learning

Output parameters
A return statement can be used for returning only one value from a function
...
Output parameters are like reference parameters, except that they transfer
data out of the method rather than into it
...
WriteLine("Before method call, value of a : {0}", a);
/* calling a function to get the value */
n
...
WriteLine("After method call, value of a : {0}", a);
Console
...
Output parameters are
particularly useful when you need to return values from a method through the parameters without assigning an initial
value to the parameter
...
WriteLine("Enter the first value: ");
x = Convert
...
ReadLine());
Console
...
ToInt32(Console
...
getValues(out a, out b);
Console
...
WriteLine("After method call, value of b : {0}", b);
Console
...

For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable< Int32 > 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

TUTORIALS POINT
Simply Easy Learning

CHAPTER

15
C# Arrays

A

n array stores a fixed-size sequential collection of elements of the same type
...

Instead of declaring individual variables, such as number0, number1,
...
, numbers[99] to represent individual variables
...

All arrays consist of contiguous memory locations
...


Declaring Arrays
To declare an array in C#, you can use the following syntax:
datatype[] arrayName;
where,

 datatype is used to specify the type of elements to be stored in the array
...
The rank specifies the size of the array
...

For example,
double[] balance;

Initializing an Array
Declaring an array does not initialize the array in the memory
...

Array is a reference type, so you need to use the new keyword to create an instance of the array
...
0;
You can assign values to the array at the time of declaration, like:
double[] balance = { 2340
...
69, 3421
...
In that case, both the target and source would
point to the same memory location:
int [] marks = new int[]
int[] score = marks;

{ 99,

98, 92, 97, 95};

When you create an array, C# compiler implicitly initializes each array element to a default value depending on the
array type
...


Accessing Array Elements
An element is accessed by indexing the array name
...
For example:
double salary = balance[9];
Following is an example, which will use all the above-mentioned three concepts viz
...
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
...
There are following few important concepts related to
array which should be clear to a C# programmer:
Concept

Description

Multi-dimensional arrays

C# supports multidimensional arrays
...


Jagged arrays

C# supports multidimensional arrays, which are arrays of arrays
...


Param arrays

This is used for passing unknown number of parameters to a function
...


Multi-dimensional arrays
C# allows multidimensional arrays
...

You can declare a 2-dimensional array of strings as:
string [,] names;
or, a 3-dimensional array of int variables:
int [ , , ] m;

Two-Dimensional Arrays:
The simplest form of the multidimensional array is the 2-dimensional array
...

A 2-dimensional array can be thought of as a table, which will have x number of rows and y number of columns
...


Initializing Two-Dimensional Arrays
Multidimensional arrays may be initialized by specifying bracketed values for each row
...

int [,]
{0, 1,
{4, 5,
{8, 9,
};

a = int [3,4] = {
2, 3} ,
/* initializers for row indexed by 0 */
6, 7} ,
/* initializers for row indexed by 1 */
10, 11}
/* initializers for row indexed by 2 */

Accessing Two-Dimensional Array Elements
An element in 2-dimensional array is accessed by using the subscripts, i
...
, 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 scores of int values as:
int [][] scores;
Declaring an array, does not create the array in memory
...
Length; x++)
{
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]);
}
}

TUTORIALS POINT
Simply Easy Learning

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;
/* 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)
{
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 provides some of the most commonly used properties of the Array class:
S
...


TUTORIALS POINT
Simply Easy Learning

2

IsReadOnly
Gets a value indicating whether the Array is read-only
...


4

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


Methods of the Array Class
The following table provides some of the most commonly used properties of the Array class:
S
...


2

Copy(Array, Array, Int32)
Copies a range of elements from an Array starting at the first element and pastes them into another Array
starting at the first element
...


3

CopyTo(Array, Int32)
Copies all the elements of the current one-dimensional Array to the specified one-dimensional Array starting
at the specified destination Array index
...


4

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


6

GetLowerBound
Gets the lower bound of the specified dimension in the Array
...
(Inherited from Object
...


9

GetValue(Int32)
Gets the value at the specified position in the one-dimensional Array
...


10

IndexOf(Array, Object)
Searches for the specified object and returns the index of the first occurrence within the entire onedimensional Array
...


12

SetValue(Object, Int32)
Sets a value to the element at the specified position in the one-dimensional Array
...


TUTORIALS POINT
Simply Easy Learning

13

Sort(Array)
Sorts the elements in an entire one-dimensional Array using the IComparable implementation of each
element of the Array
...
(Inherited from Object
...


Example
The following program demonstrates use of some of the methods of the Array class:
using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int[] list = { 34, 72, 13, 44, 25, 30, 10 };
int[] temp = list;
Console
...
Write(i + " ");
}
Console
...
Reverse(temp);
Console
...
Write(i + " ");
}
Console
...
Sort(list);
Console
...
Write(i + " ");
}
Console
...
ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Original Array: 34 72 13 44 25 30 10
Reversed Array: 10 30 25 44 13 72 34
Sorted Array: 10 13 25 30 34 44 72

TUTORIALS POINT
Simply Easy Learning

TUTORIALS POINT
Simply Easy Learning

CHAPTER

16
C# Strings

I

n C#, you can use strings as array of characters, however, more common practice is to use the string keyword

to declare a string variable
...
String class
...
WriteLine("Full Name: {0}", fullname);
//by using string constructor
char[] letters = { 'H', 'e', 'l', 'l','o' };
string greetings = new string(letters);
Console
...
Join(" ", sarray);
Console
...
Format("Message sent at {0:t} on {0:D}",
waiting);
Console
...
ReadKey() ;
}
}
}
When the above code is compiled and executed, it produces the following result:
Full Name: Rowan Atkinson
Greetings: Hello
Message: Hello From Tutorials Point
Message: Message sent at 5:58 PM on Wednesday, October 10, 2012

Properties of the String Class
The String class has the following two properties:
S
...


2

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


2

public static int Compare( string strA, string strB, bool ignoreCase )
Compares two specified string objects and returns an integer that indicates their relative position in the sort
order
...


3

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


5

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


7

public static string Copy( string str )
Creates a new String object with the same value as the specified string
...


9

public bool EndsWith( string value )
Determines whether the end of the string object matches the specified string
...


11

public static bool Equals( string a, string b )
Determines whether two specified string objects have the same value
...


13

public int IndexOf( char value )
Returns the zero-based index of the first occurrence of the specified Unicode character in the current string
...


15

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


17

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


19

public string Insert( int startIndex, string value )
Returns a new string in which a specified string is inserted at a specified index position in the current string
object
...


21

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


23

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


25

public string Remove( int startIndex )
Removes all the characters in the current instance, beginning at a specified position and continuing through
the last position, and returns the string
...


27

public string Replace( char oldChar, char newChar )
Replaces all occurrences of a specified Unicode character in the current string object with the specified
Unicode character and returns the new string
...


29

public string[] Split( params char[] separator )
Returns a string array that contains the substrings in the current string object, delimited by elements of a
specified Unicode character array
...
The int parameter specifies the maximum number of substrings to return
...


32

public char[] ToCharArray()
Returns a Unicode character array with all the characters in the current string object
...


34

public string ToLower()
Returns a copy of this string converted to lowercase
...


36

public string Trim()
Removes all leading and trailing white-space characters from the current String object
...


Examples:
The following example demonstrates some of the methods mentioned above:

Comparing Strings:
using System;
namespace StringApplication
{
class StringProg

TUTORIALS POINT
Simply Easy Learning

{
static void Main(string[] args)
{
string str1 = "This is test";
string str2 = "This is text";
if (String
...
WriteLine(str1 + " and " + str2 + " are equal
...
WriteLine(str1 + " and " + str2 + " are not equal
...
ReadKey() ;
}
}
}
When the above code is compiled and executed, it produces the following result:
This is test and This is text are not equal
...
Contains("test"))
{
Console
...
");
}
Console
...


Getting a Substring:
using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str = "Last night I dreamt of San Pedro";
Console
...
Substring(23);
Console
...
ReadKey() ;
}
}
When the above code is compiled and executed, it produces the following result:
San Pedro

Joining Strings:
using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string[] starray = new string[]{"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"};
string str = String
...
WriteLine(str);
}
Console
...
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 would 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;
public string subject;

TUTORIALS POINT
Simply Easy Learning

public int book_id;
};
public class testStructure
{
public static void Main(string[] args)
{
Books Book1;
Books Book2;

/* Declare Book1 of type Book */
/* 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);
/* print Book2 info */
Console
...
WriteLine("Book
Console
...
WriteLine("Book

2
2
2
2

title : {0}", Book2
...
author);
subject : {0}", Book2
...
book_id);

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


TUTORIALS POINT
Simply Easy Learning



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




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 vs 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()
{
Console
...
WriteLine("Author : {0}", author);
Console
...
WriteLine("Book_id :{0}", book_id);
}
};
public class testStructure
{

TUTORIALS POINT
Simply Easy Learning

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();
Console
...
An enumerated type is declared using the enum

keyword
...
In other words, enumeration contains its own values and cannot inherit or
cannot pass inheritance
...

 The enumeration list is a comma-separated list of identifiers
...

By default, the value of the first enumeration symbol is 0
...
Mon;
int WeekdayEnd = (int)Days
...
WriteLine("Monday: {0}", WeekdayStart);

TUTORIALS POINT
Simply Easy Learning

Console
...
ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Monday: 1
Friday: 5

TUTORIALS POINT
Simply Easy Learning

CHAPTER

19
C# Classes

W

hen you define a class, you define a blueprint for a data type
...
Objects are instances of a class
...


Class Definition
A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of
curly braces
...

variableN;
// member methods
method1(parameter_list)
{
// method body
}
method2(parameter_list)
{
// method body
}

...
Default access for the members is private
...


TUTORIALS POINT
Simply Easy Learning



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




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

Length of a box
Breadth of a box
Height of a box

args)
// Declare Box1 of type Box
// Declare Box2 of type Box
// 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
...
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();
}
}
}

TUTORIALS POINT
Simply Easy Learning

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

Constructors in C#
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;
public Line(double len)

TUTORIALS POINT
Simply Easy Learning

// Length of a line
//Parameterized constructor

{
Console
...
0);
Console
...
getLength());
// set line length
line
...
0);
Console
...
getLength());
Console
...
A destructor will have exact same name as the class prefixed with a 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();

TUTORIALS POINT
Simply Easy Learning

s2
...
WriteLine("Variable num for s1: {0}", s1
...
WriteLine("Variable num for s2: {0}", s2
...
ReadKey();
}
}
}
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 allows

us to define a class in terms of another class, which makes it easier to create and maintain an application
...

When creating a class, instead of writing completely new data members and member functions, the programmer can
designate that the new class should inherit the members of an existing class
...

The idea of inheritance implements the IS-A relationship
...


Base and Derived Classes
A class can be derived from more than one class or interface, which means that it can inherit data and functions from
multiple base class or interface
...

}
class :
{

...
setWidth(5);
Rect
...

Console
...
ReadKey();

Rect
...
Therefore the super class object
should be created before the subclass is created
...

The following program demonstrates this:
using System;
namespace RectangleApplication
{
class Rectangle
{
//member variables
protected double length;
protected double width;
public Rectangle(double l, double w)
{
length = l;
width = w;
}
public double GetArea()
{
return length * width;

TUTORIALS POINT
Simply Easy Learning

}
public void Display()
{
Console
...
WriteLine("Width: {0}", width);
Console
...
Display();
Console
...
5, 7
...
Display();
Console
...
5
Width: 7
...
75
Cost: 2362
...
However, you can use interfaces to implement multiple inheritance
...
setWidth(5);
Rect
...
getArea();
// Print the area of the object
...
WriteLine("Total area: {0}", Rect
...
WriteLine("Total paint cost: ${0}" , Rect
...
ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Total area: 35
Total paint cost: $2450

TUTORIALS POINT
Simply Easy Learning

CHAPTER

21
C# Polymorphism

T

he 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
...
These are:



Function overloading



Operator overloading

We will discuss function overloading in the next section and operator overloading will be dealt with 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
...

Following is the example where same function print() is being used 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)
{

TUTORIALS POINT
Simply Easy Learning

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
...
Thus a programmer can use

operators with user-defined types as well
...
Like any other function, an overloaded
operator has a return type and a parameter list
...
length = b
...
length;
box
...
breadth + c
...
height = b
...
height;
return box;
}
The above function implements the addition operator (+) for a user-defined class Box
...


Implementation of Operator Overloading
The following program shows the complete implementation:
using System;
namespace OperatorOvlApplication
{
class Box
{
private double length;
private double breadth;
private double height;

// Length of a box
// Breadth of a box
// Height of a box

public double getVolume()
{
return length * breadth * height;
}
public void setLength( double len )
{
length = len;
}

TUTORIALS POINT
Simply Easy Learning

public void setBreadth( double bre )
{
breadth = bre;
}
public void setHeight( double hei )
{
height = hei;
}
// Overload + operator to add two Box objects
...
length = b
...
length;
box
...
breadth + c
...
height = b
...
height;
return box;
}
}
class Tester
{
static void Main(string[] args)
{
Box Box1 = new Box();
Box Box2 = new Box();
Box Box3 = new Box();
double volume = 0
...
setLength(6
...
setBreadth(7
...
setHeight(5
...
setLength(12
...
setBreadth(13
...
setHeight(10
...
getVolume();
Console
...
getVolume();
Console
...
getVolume();
Console
...
ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:

TUTORIALS POINT
Simply Easy Learning

Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400

Overloadable and Non-Overloadable Operators
The following table describes the overload ability of the operators in C#:
Operators

Description

+, -, !, ~, ++, --

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


==, !=, <, >, <=, >=

The comparison operators can be overloaded

&&, ||

The conditional logical operators cannot be overloaded directly
...


=,
...


Example:
In the light of the above discussions, let us extend the preceding example, and overload few more operators:
using System;
namespace OperatorOvlApplication
{
class Box
{
private double length;
private double breadth;
private double height;

// Length of a box
// Breadth of a box
// Height of a box

public double getVolume()
{
return length * breadth * height;
}
public void setLength( double len )
{
length = len;
}
public void setBreadth( double bre )
{
breadth = bre;
}
public void setHeight( double hei )
{
height = hei;
}
// Overload + operator to add two Box objects
...
length = b
...
length;
box
...
breadth + c
...
height = b
...
height;
return box;
}
public static bool operator == (Box lhs, Box rhs)
{
bool status = false;
if (lhs
...
length && lhs
...
height
&& lhs
...
breadth)
{
status = true;
}
return status;
}
public static bool operator !=(Box lhs, Box rhs)
{
bool status = false;
if (lhs
...
length || lhs
...
height
|| lhs
...
breadth)
{
status = true;
}
return status;
}
public static bool operator <(Box lhs, Box rhs)
{
bool status = false;
if (lhs
...
length && lhs
...
height && lhs
...
breadth)
{
status = true;
}
return status;
}
public static bool operator >(Box lhs, Box rhs)
{
bool status = false;
if (lhs
...
length && lhs
...
height && lhs
...
breadth)
{
status = true;
}
return status;
}
public static bool operator <=(Box lhs, Box rhs)
{
bool status = false;
if (lhs
...
length && lhs
...
height && lhs
...
breadth)
{
status = true;
}
return status;
}
public static bool operator >=(Box lhs, Box rhs)
{
bool status = false;
if (lhs
...
length && lhs
...
height && lhs
...
breadth)
{
status = true;
}
return status;
}
public override string ToString()
{
return String
...
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);
//displaying the Boxes using the overloaded ToString():
Console
...
ToString());
Console
...
ToString());
// volume of box 1
volume = Box1
...
WriteLine("Volume of Box1 : {0}", volume);
// volume of box 2
volume = Box2
...
WriteLine("Volume of Box2 : {0}", volume);
// Add two object as follows:
Box3 = Box1 + Box2;
Console
...
ToString());
// volume of box 3
volume = Box3
...
WriteLine("Volume of Box3 : {0}", volume);
//comparing the boxes
if (Box1 > Box2)
Console
...
WriteLine("Box1
if (Box1 < Box2)
Console
...
WriteLine("Box1

TUTORIALS POINT
Simply Easy Learning

is greater than Box2");
is

greater than Box2");

is less than Box2");
is not less than Box2");

if (Box1 >= Box2)
Console
...
WriteLine("Box1
if (Box1 <= Box2)
Console
...
WriteLine("Box1
if (Box1 != Box2)
Console
...
WriteLine("Box1
Box4 = Box3;
if (Box3 == Box4)
Console
...
WriteLine("Box3

is greater or equal to Box2");
is not greater or equal to Box2");
is less or equal to Box2");
is not less or equal to Box2");
is not equal to Box2");
is not greater or equal to Box2");
is equal to Box4");
is not equal to Box4");

Console
...
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()
{
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

TUTORIALS POINT
Simply Easy Learning

CHAPTER

24
C# Namespaces

A

namespace is designed for providing a way to keep one set of names separate from another
...


Defining a Namespace
A namespace definition begins with the keyword namespace followed by the namespace name as follows:
namespace namespace_name
{
// code declarations
}
To call the namespace-enabled version of either function or variable, prepend the namespace name as follows:
namespace_name
...
WriteLine("Inside first_space");
}
}
}
namespace second_space
{
class namespace_cl
{
public void func()
{
Console
...
namespace_cl fc = new first_space
...
namespace_cl sc = new second_space
...
func();
sc
...
ReadKey();
}
}
When the above code is compiled and executed, it produces the following result:
Inside first_space
Inside second_space

The using Keyword
The using keyword states that the program is using the names in the given namespace
...
The class Console is defined there
...
WriteLine ("Hello there");
We could have written the fully qualified name as:
System
...
WriteLine("Hello there");
You can also avoid prepending of namespaces with the using namespace directive
...
The namespace is thus implied for the
following code:
Let us rewrite our preceding example, with using directive:
using System;
using first_space;
using second_space;
namespace first_space
{
class abc
{
public void func()
{
Console
...
WriteLine("Inside second_space");
}
}
}
class TestClass
{
static void Main(string[] args)

TUTORIALS POINT
Simply Easy Learning

{
abc fc = new abc();
efg sc = new efg();
fc
...
func();
Console
...
) operator as follows:
using System;
using first_space;
using first_space
...
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

TUTORIALS POINT
Simply Easy Learning

CHAPTER

25
C# Preprocessor Directives

T

he preprocessors 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 will evaluate to true
...
WriteLine("PI is defined");
#else
Console
...
ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
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
...
The
...
A pattern consists of one or more character literals, operators,
or constructs
...
Click
the follwoing links to find these constructs
...
The backslash character (\) in a regular expression
indicates that the character that follows it either is a special character or should be interpreted literally
...


\a

"\u0007" in "Warning!" +
'\u0007'

\b

In a character class, matches a backspace, \u0008
...


(\w+)\t

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

\r

Matches a carriage return, \u000D
...
)

\r\n(\w+)

"\r\nHello" in
"\r\Hello\nWorld
...


[\v]{2,}

"\v\v\v" in "\v\v\v"

\f

Matches a form feed, \u000C
...


\r\n(\w+)

"\r\nHello" in
"\r\Hello\nWorld
...


\e

"\x001B" in "\x001B"

\ nnn

Uses octal representation to specify a character (nnn
consists of up to three digits)
...


\w\x20\w

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

\c X \c x

Matches the ASCII control character that is specified by
X or x, where X or x is the letter of the control character
...


\w\u0020\w

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

\

When followed by a character that is not recognized as
an escaped character, matches that character
...
The following table describes the character classes:
Character class

Description

Pattern

Matches

[character_group]

Matches any single character in character_group
...


[mn]

"m" in "mat" "m", "n"
in "moon"

[^character_group]

Negation: Matches any single character that is not in
character_group
...


[^aei]

"v", "l" in "avail"

[ first - last ]

Character range: Matches any single character in the
range from first to last
...


Wildcard: Matches any single character except \n
...
e

"ave" in "have" "ate"
in "mate"

\p{ name }

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


\P{Lu}

"i", "t", "y" in "City"

\w

Matches any word character
...


\W

"#" in "Room#1"

\s

Matches any white-space character
...
3"

\S

Matches any non-white-space character
...


\d

"4" in "4 = IV"

TUTORIALS POINT
Simply Easy Learning

\D

Matches any character other than a decimal digit
...
The following table lists the
anchors:
Assertion Description

Pattern

Matches

^

The match must start at the beginning of the string or line
...


-\d{4}$

"-2012" in "8-12-2012"

\A

The match must occur at the start of the string
...


-\d{3}\Z

"-007" in "Bond-901-007"

\z

The match must occur at the end of the string
...


\\G\(\d\)

"(1)", "(3)", "(5)" in
"(1)(3)(5)[7](9)"

\b

The match must occur on a boundary between
a \w (alphanumeric) and a\W(nonalphanumeric)
character
...


\Bend\w*\b

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

Grouping constructs
Grouping constructs delineate sub-expressions of a regular expression and capture substrings of an input string
...


(\w)\1

"ee" in "deep"

(?< name
>subexpression)

Captures the matched
subexpression into a
named group
...


(((?'Open'\()[^\(\)]*)+((?'CloseOpen'\))[^\(\)]*)+)*(?(Open)(?!))$

"((1-3)*(3-1))" in
"3+2^((1-3)*(3-1))"

(?: subexpression)

Defines a noncapturing
group
...
WriteLine()"

(?imnsximnsx:subexpression)

Applies or disables the
specified options
withinsubexpression
...


\w+(?=\
...
The dog ran
...
"

(?! subexpression)

Zero-width negative
lookahead assertion
...


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

"51", "03" in "1851 1999
1950 1905 2003"

(?< ! subexpression)

Zero-width negative
lookbehind assertion
...


[13579](?>A+B+)

"1ABB", "3ABB", and
"5AB" in "1ABB 3ABBC
5AB 5AC"

Quantifiers
Quantifiers specify how many instances of the previous element (which can be a character, a group, or a character
class) must be present in the input string for a match to occur
...


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

+

Matches the previous element one or more
times
...


"rai?n"

"ran", "rain"

{n}

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

{ n ,}

Matches the previous element at least n times
...


"\d{3,5}"

"166", "17668" "19302" in "193024"

*?

Matches the previous element zero or more
times, but as few times as possible
...
\d

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


"be+?"

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

??

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


",\d{3}?"

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


"\d{2,}?"

"166", "29", "1930"

{ n , m }?

Matches the previous element between n and
m times, but as few times as possible
...

The following table lists these constructs:
Backreference
construct

Description

Pattern

Matches

\ number

Backreference
...


(\w)\1

"ee" in "seek"

\k< name >

Named backreference
...


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

"ee" in "seek"

Alternation constructs
Alternation constructs modify a regular expression to enable either/or matching
...


"the", "this" in "this is
the day
...

Expression is interpreted as a zerowidth assertion
...


(?<
quoted>")?(?(quoted)
...
jpg, "Yiska
playing
...
jpg "Yiska
playing
...
The following table lists the substitutions:
Character Description

Pattern

Replacement
pattern

Input string

Result string

$number

Substitutes the substring
matched by group
number
...


\b(?<
word1>\w+)(\s)(?<
word2>\w+)\b

${word2}
${word1}

"one two"

"two one"

$$

Substitutes a literal "$"
...


(\$*(\d*(\
...
30"

"**$1
...


B+

$`

"AABBCC"

"AAAACC"

$'

Substitutes all the text of
the input string after the
match
...


B+(C+)

$+

"AABBCCDD" AACCDD

$_

Substitutes the entire
input string
...


\bA(?i)b\w+\b matches "ABA", "Able" in
"ABA Able Act"

(?#comment)

Inline comment
...


\bA(?#Matches words starting with
A)\w+\b

# [to end of line]

X-mode comment
...


(?x)\bA\w+\b#Matches words starting
with A

The Regex Class
The Regex class is used for representing a regular expression
...
N Methods & Description
1

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


TUTORIALS POINT
Simply Easy Learning

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();
}
}
}
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
...
A C# exception is a response to

an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero
...
C# exception handling is built
upon four keywords: try, catch, finally and throw
...
It's followed by one or
more catch blocks
...
The catch keyword indicates the catching of an exception
...
For example, if you open a file, it must be closed whether an exception is raised or not
...
This is done using a throw keyword
...
A try/catch block is placed around the code that might generate an exception
...


Exception Classes in C#
C# exceptions are represented by classes
...
Exception class
...
Exception class are
the System
...
SystemException classes
...
ApplicationException class supports exceptions generated by application programs
...

The System
...

The following table provides some of the predefined exception classes derived from the Sytem
...
IO
...


System
...


System
...


System
...


System
...


System
...


System
...


System
...


Handling Exceptions
C# provides a structured solution to the exception handling problems in the form of try and catch blocks
...

These error handling blocks are implemented using the try, catch and finally keywords
...
WriteLine("Exception caught: {0}", e);
}
finally
{
Console
...
division(25, 0);
Console
...
DivideByZeroException: Attempted to divide by zero
...

Result: 0

Creating User-Defined Exceptions
You can also define your own exception
...
The following example demonstrates this:

classes

using System;
namespace UserDefinedException
{
class TestTemperature
{
static void Main(string[] args)
{
Temperature temp = new Temperature();
try
{
temp
...
WriteLine("TempIsZeroException: {0}", e
...
ReadKey();
}
}
}
public class TempIsZeroException: ApplicationException
{
public TempIsZeroException(string message): base(message)
{
}
}
public class Temperature
{
int temperature = 0;
public void showTemp()
{
if(temperature == 0)

TUTORIALS POINT
Simply Easy Learning

are

derived

from

{
throw (new TempIsZeroException("Zero Temperature found"));
}
else
{
Console
...
Exception class
...

Throw e
}

TUTORIALS POINT
Simply Easy Learning

CHAPTER

28
C# 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 class that are used for performing various operation with files,
like 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
...


TUTORIALS POINT
Simply Easy Learning

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:
FileStream F = new FileStream("sample
...
Open, FileAccess
...
Read);
Parameter

Description

FileMode

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",

TUTORIALS POINT
Simply Easy Learning

FileMode
...
ReadWrite);
for (int i = 1; i <= 20; i++)
{
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
...
Please click the
links provided to get to the individual sections:
Topic and Description
Reading from and Writing into Text files
It involves reading from and writing into text files
...

Reading from and Writing into Binary files
It involves reading from and writing into binary files
...

Manipulating the Windows file system
It gives a C# programamer the ability to browse and locate Windows files and directories
...
These classes
inherit from the abstract base class Stream, which supports reading and writing bytes into a file stream
...
The following table describes some of the commonly usedmethods of the StreamReader class:

TUTORIALS POINT
Simply Easy Learning

S
...


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
And the sun shines
I took a trip on a
And when I reached
I made a stop
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!

TUTORIALS POINT
Simply Easy Learning

The StreamWriter Class
The StreamWriter class inherits from the abstract class TextWriter that represents a writer, which can write a series
of character
...
N Method Name & Purpose
1

public override void Close()
Closes the current StreamWriter object and the underlying stream
...


3

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

4

public override void Write( char value )
Writes a character to the stream
...


6

public virtual void Write( double value )
Writes the text representation of an 8-byte floating-point value to the text string or stream
...


8

public override void Write( string value )
Writes a string to the stream
...


For complete list of methods, please visit Microsoft's C# documentation
...
IO;
namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
string[] names = new string[] {"Zara Ali", "Nuha Ali"};
using (StreamWriter sw = new StreamWriter("names
...
WriteLine(s);
}
}

TUTORIALS POINT
Simply Easy Learning

// Read and show each line from the file
...
txt"))
{
while ((line = sr
...
WriteLine(line);
}
}
Console
...


The BinaryReader Class
The BinaryReader class is used to read binary data from a file
...

The following table shows some of the commonly used methods of the BinaryReader class
...
N Method Name & Purpose
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
...


TUTORIALS POINT
Simply Easy Learning

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

S
...


2

public virtual void Flush()
Clears all buffers for the current writer and causes any buffered data to be written to the underlying device
...


4

public virtual void Write( bool value )
Writes a one-byte Boolean value to the current stream, with 0 representing false and 1 representing true
...


6

public virtual void Write( byte[] buffer )
Writes a byte array to the underlying stream
...


8

public virtual void Write( char[] chars )
Writes a character array 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
...


10

public virtual void Write( int value )
Writes a four-byte signed integer to the current stream and advances the stream position by four bytes
...


For complete list of methods, please visit Microsoft's C# documentation
...
IO;
namespace BinaryFileApplication
{
class Program
{
static void Main(string[] args)
{
BinaryWriter bw;
BinaryReader br;
int i = 25;
double d = 3
...
Create));
}
catch (IOException e)
{
Console
...
Message + "\n Cannot create file
...
Write(i);
bw
...
Write(b);
bw
...
WriteLine(e
...
");
return;
}
bw
...
Open));
}
catch (IOException e)
{
Console
...
Message + "\n Cannot open file
...
ReadInt32();
Console
...
ReadDouble();
Console
...
ReadBoolean();
Console
...
ReadString();
Console
...
WriteLine(e
...
");
return;
}
br
...
ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Integer data: 25
Double data: 3
...


The DirectoryInfo Class
The DirectoryInfo class is derived from the FileSystemInfo class
...
This class cannot be inherited
...
N Property Name & Description
1

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


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
...
N Method Name & Purpose
1

public void Create()
Creates a directory
...
The specified path can be relative to this
instance of the DirectoryInfo class
...


4

public DirectoryInfo[] GetDirectories()
Returns the subdirectories of the current directory
...


For complete list of properties and methods please visit Microsoft's C# documentation
...
It has properties and instance methods for creating,
copying, deleting, moving, and opening of files, and helps in the creation of FileStream objects
...

Following are some commonly used properties of the FileInfo class:
S
...


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


8

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


10

Name
Gets the name of the file
...
N Method Name & Purpose
1

public StreamWriter AppendText()
Creates a StreamWriter that appends text to the file represented by this instance of the FileInfo
...


3

public override void Delete()
Deletes a file permanently
...


5

public FileStream Open( FileMode mode )
Opens a file in the specified mode
...


7

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


For complete list of properties and methods, please visit Microsoft's C# documentation

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 size in the Windows directory
...
, in your program
...
A declarative tag is depicted by square ([ ]) brackets placed above the
element it is used for
...
The
...


Specifying an Attribute
Syntax for specifying an attribute is as follows:
[attribute(positional_parameters, name_parameter = value,
...
Positional parameters specify the essential information and the name parameters specify the optional
information
...
Net Framework provides three pre-defined attributes:

 AttributeUsage
 Conditional
 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,

TUTORIALS POINT
Simply Easy Learning

AllowMultiple=allowmultiple,
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 AllowMultiple property 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")]
The following example demonstrates the attribute:
#define DEBUG
using System;
using System
...
WriteLine(msg);
}
}
class Test
{
static void function1()
{
Myclass
...
");
function2();
}

TUTORIALS POINT
Simply Easy Learning

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)]
static void OldMethod()
{
Console
...
WriteLine("It is the new method");
}
public static void Main()
{
OldMethod();
}

TUTORIALS POINT
Simply Easy Learning

}
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
...
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 will store the information obtained by debugging any
program
...
So the bug number, developer�s name and date of review will be the positional parameters of
the DeBugInfo class and the message will be 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;
}
}
public string LastReview
{
get
{
return lastReview;
}
}
public string Message
{
get
{
return message;
}
set
{
message = value;
}
}

TUTORIALS POINT
Simply Easy Learning

}

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


TUTORIALS POINT
Simply Easy Learning

CHAPTER

30
C# Reflection

R

eflection objects are used for obtaining type information at runtime
...
Reflection namespace
...
Reflection namespace contains classes that allow you to obtain information about the application and
to dynamically add types, values and objects to the application
...




It allows examining various types in an assembly and instantiate these types
...


Viewing Metadata
We have mentioned in the preceding chapter that using reflection you can view the attribute information
...
Reflection class need to be initialized for discovering the attributes
asscociated with a class
...
Reflection
...
All)]
public class HelpAttribute : System
...
Url = url;
}

// url is a positional parameter

private string topic;
}
[HelpAttribute("Information on the class MyClass")]
class MyClass
{
}
namespace AttributeAppl
{
class Program
{
static void Main(string[] args)
{
System
...
MemberInfo info = typeof(MyClass);
object[] attributes = info
...
Length; i++)
{
System
...
WriteLine(attributes[i]);
}
Console
...

using System;
using System
...
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;
}
}
public string LastReview
{
get
{
return lastReview;
}
}
public string Message
{
get
{
return message;
}
set
{
message = value;
}
}
}
[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
protected double length;
protected double width;
public Rectangle(double l, double w)
{

TUTORIALS POINT
Simply Easy Learning

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
...
5, 7
...
Display();
Type type = typeof(Rectangle);
//iterating through the attribtues of the Rectangle class
foreach (Object attributes in type
...
WriteLine("Bug no: {0}", dbi
...
WriteLine("Developer: {0}", dbi
...
WriteLine("Last Reviewed: {0}",
dbi
...
WriteLine("Remarks: {0}", dbi
...
GetMethods())
{
foreach (Attribute a in m
...
WriteLine("Bug no: {0}, for Method: {1}",
dbi
...
Name);
Console
...
Developer);
Console
...
LastReview);
Console
...
Message);
}
}
}
Console
...
5
Width: 7
...
75
Bug No: 49
Developer: Nuha Ali
Last Reviewed: 10/10/2012
Remarks: Unused variable
Bug No: 45
Developer: Zara Ali
Last Reviewed: 12/8/2012
Remarks: Return type mismatch
Bug No: 55, for Method: GetArea
Developer: Zara Ali
Last Reviewed: 19/10/2012
Remarks: Return type mismatch
Bug No: 56, for Method: Display
Developer: Zara Ali
Last Reviewed: 19/10/2012
Remarks:

TUTORIALS POINT
Simply Easy Learning

CHAPTER

31
C# Properties

P

roperties are named members of classes, structures and interfaces
...
Properties are an extension of fields and are accessed using the same syntax
...

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:
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
// Declare a Age property of type int:
public int Age

TUTORIALS POINT
Simply Easy Learning

{
get
{
return age;
}
set
{
age = value;
}
}

Example:
The following example demonstrates use of properties:
using System;
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

TUTORIALS POINT
Simply Easy Learning

TUTORIALS POINT
Simply Easy Learning

CHAPTER

32
C# Indexers

A

n indexer allows an object to be indexed like an array
...
You can then access the instance of this class using the array access operator ([ ])
...

get
{
// return the value specified by index
}
// The set accessor
...
Like properties, you use
get and set accessors for defining an indexer
...
In other words, it breaks the instance data into
smaller parts and indexes each part, gets or sets each part
...
Indexers are not defined with names, but with
the this keyword, which refers to the object instance
...
A
...
size; i++ )
{
Console
...
ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N
...

N
...


TUTORIALS POINT
Simply Easy Learning

N
...


Overloaded Indexers
Indexers can be overloaded
...
It is not necessary that the indexes have to be integers
...

The following example demonstrates overloaded indexers:
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 );
}
set
{
if( index >= 0 && index <= size-1 )
{
namelist[index] = value;
}
}
}
public int this[string name]
{
get
{
int index = 0;
while(index < size)
{
if (namelist[index] == name)
{
return index;

TUTORIALS POINT
Simply Easy Learning

}
index++;
}
return index;
}
}
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";
//using the first indexer with int parameter
for (int i = 0; i < IndexedNames
...
WriteLine(names[i]);
}
//using the second indexer with the string parameter
Console
...
ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N
...

N
...

N
...

2

TUTORIALS POINT
Simply Easy Learning

CHAPTER

33
C# 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 string parameter and returns an int type
variable
...
When creating a delegate, the argument passed to the new expression is written like 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 useful 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)
{
num += p;

TUTORIALS POINT
Simply Easy Learning

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();
}
}
}
When the above code is compiled and executed, it produces the following result:
Value of Num: 75

Use of Delegate
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)

TUTORIALS POINT
Simply Easy Learning

{
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

TUTORIALS POINT
Simply Easy Learning

CHAPTER

34
C# Events

E

vents are basically a user action like key press, clicks, mouse movements, etc
...
Applications need to respond to events when they occur
...

Events are used for inter-process communication
...
The class containing the event is used to publish the event
...
Some other class that accepts this event is called the subscriber class
...

A publisher is an object that contains the definition of the event and the delegate
...
A publisher class object invokes the event and it is notified to other objects
...
The delegate in the publisher class
invokes the method (event handler) of the subscriber class
...
For example,
public delegate void BoilerLogHandler(string status);
Next, the event itself is declared, using the event keyword:
//Defining event based on the above delegate
public event BoilerLogHandler BoilerEventLog;
The preceding code defines a delegate named BoilerLogHandler and an event named BoilerEventLog, which invokes
the delegate when it is raised
...
WriteLine("Event fired!");
}
}
public EventTest(int n )
{
SetValue(n);
}
public void SetValue(int n)
{
if (value != n)
{
value = n;
OnNumChanged();
}
}
}
public class MainClass
{
public static void Main()
{
EventTest e = new EventTest(5);
e
...
SetValue(11);
Console
...
When the maintenance
engineer inspects the boiler, the boiler temperature and pressure is automatically recorded into a log file along with
the remarks of the maintenance engineer
...
IO;
namespace BoilerEventAppl
{
// boiler class

TUTORIALS POINT
Simply Easy Learning

class Boiler
{
private int temp;
private int pressure;
public Boiler(int t, int p)
{
temp = t;
pressure = p;
}
public int getTemp()
{
return temp;
}
public int getPressure()
{
return pressure;
}
}
// event publisher
class DelegateBoilerEvent
{
public delegate void BoilerLogHandler(string status);
//Defining event based on the above delegate
public event BoilerLogHandler BoilerEventLog;
public void LogProcess()
{
string remarks = "O
...
getTemp();
int p = b
...
Append, FileAccess
...
WriteLine(info);
}
public void Close()
{
sw
...
Close();
}
}
// The event subscriber
public class RecordBoilerInfo
{
static void Logger(string info)
{
Console
...
txt");
DelegateBoilerEvent boilerEvent = new DelegateBoilerEvent();
boilerEvent
...
BoilerLogHandler(Logger);
boilerEvent
...
BoilerLogHandler(filelog
...
LogProcess();
Console
...
Close();
}//end of main
}//end of RecordBoilerInfo
}
When the above code is compiled and executed, it produces the following result:
Logging info:
Temperature 100
Pressure 12
Message: O
...
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
...


Various 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, add, search and sort 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
...


SortedList

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 calledpopping the item
...

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


TUTORIALS POINT
Simply Easy Learning

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 allow 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:
S
...


2

public virtual void AddRange( ICollection c );
Adds the elements of an ICollection to the end of the ArrayList
...


4

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


6

public virtual int IndexOf(object);
Returns the zero-based index of the first occurrence of a value in the ArrayList or in a portion of it
...


8

public virtual void InsertRange( int index, ICollection c );
Inserts the elements of a collection into the ArrayList at the specified index
...


TUTORIALS POINT
Simply Easy Learning

10

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


12

public virtual void Reverse();
Reverses the order of the elements in the ArrayList
...


14

public virtual void Sort();
Sorts the elements in the ArrayList
...


Example:
The following example demonstrates the concept:
using System;
using System
...
WriteLine("Adding some numbers:");
al
...
Add(78);
al
...
Add(56);
al
...
Add(23);
al
...
WriteLine("Capacity: {0} ", al
...
WriteLine("Count: {0}", al
...
Write("Content: ");
foreach (int i in al)
{
Console
...
WriteLine();
Console
...
Sort();
foreach (int i in al)
{
Console
...
WriteLine();
Console
...
It uses the key to access the elements in the collection
...
Each
item in the hash table has a key/value pair
...


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

Description

Count

Gets the number of key-and-value pairs contained in the Hashtable
...


IsReadOnly

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


Keys

Gets an ICollection containing the keys in the Hashtable
...


The following table lists some of the commonly used methods of the Hashtable class:
S
...


2

public virtual void Clear();
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",
ht
...
Add("003",
ht
...
Add("005",
ht
...
Add("007",

"Zara Ali");
"Abida Rehman");
"Joe Holzner");
"Mausam Benazir Nur");
"M
...
Arif");
"Ritesh Saikia");

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

ICollection key = ht
...
WriteLine(k + ": " + ht[k]);
}
Console
...
Amlan
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
...


TUTORIALS POINT
Simply Easy Learning

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

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
...
N Method Name & Purpose
1

public virtual void Add( object key, object value );
Adds an element with the specified key and value into the SortedList
...


3

public virtual bool ContainsKey( object key );
Determines whether the SortedList contains a specific key
...


5

public virtual object GetByIndex( int index );
Gets the value at the specified index of the SortedList
...


7

public virtual IList GetKeyList();
Gets the keys in the SortedList
...


9

public virtual int IndexOfKey( object key );
Returns the zero-based index of the specified key in the SortedList
...


11

public virtual void Remove( object key );
Removes the element with the specified key from the SortedList
...


TUTORIALS POINT
Simply Easy Learning

public virtual void TrimToSize();
Sets the capacity to the actual number of elements in the SortedList
...
Collections;
namespace CollectionsApplication
{
class Program
{
static void Main(string[] args)
{
SortedList sl = new SortedList();
sl
...
Add("002",
sl
...
Add("004",
sl
...
Add("006",
sl
...
Amlan");
"M
...
ContainsValue("Nuha Ali"))
{
Console
...
Add("008", "Nuha Ali");
}
// get a collection of the keys
...
Keys;
foreach (string k in key)
{
Console
...
Amlan
M
...
It is used when you need a last-in, first-out access of items
...


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

Description

Count

Gets the number of elements contained in the Stack
...
N Method Name & Purpose
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');
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 first-in, 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

Description

Count

Gets the number of elements contained in the Queue
...
N Method Name & Purpose
1

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


3

public virtual object Dequeue();
Removes and returns the object at the beginning of the Queue
...


5

public virtual object[] ToArray();
Copies the Queue to a new array
...


Example:
The following example demonstrates use of Stack:
using System;
using System
...
Enqueue('A');
q
...
Enqueue('G');
q
...
WriteLine("Current queue: ");
foreach (char c in q)
Console
...
WriteLine();
q
...
Enqueue('H');
Console
...
Write(c + " ");
Console
...
WriteLine("Removing some values ");
char ch = (char)q
...
WriteLine("The removed value: {0}", ch);
ch = (char)q
...
WriteLine("The removed value: {0}", ch);
Console
...

It is used when you need to store the bits but do not know the number of bits in advance
...


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

Description

Count

Gets the number of elements contained in the BitArray
...


Item

Gets or sets the value of the bit at a specific position in the BitArray
...


The following table lists some of the commonly used methods of the BitArray class:
S
...


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:

TUTORIALS POINT
Simply Easy Learning

using System;
using System
...
WriteLine("Bit array ba1: 60");
for (int i = 0; i < ba1
...
Write("{0, -6} ", ba1[i]);
}
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]);
}
Console
...
ReadKey();
}
}
}

TUTORIALS POINT
Simply Easy Learning

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

TUTORIALS POINT
Simply Easy Learning

CHAPTER

36
C# Generics

G

enerics allow you to delay the specification of the data type of programming elements in a class or a method

until it is actually used in the program
...

You write the specifications for the class or the method, with substitute parameters for data types
...
A simple example would help understanding the concept:
using System;
using System
...
Generic;
namespace GenericApplication
{
public class MyGenericArray
{
private T[] array;
public MyGenericArray(int size)
{
array = new T[size + 1];
}
public T getItem(int index)
{
return array[index];
}
public void setItem(int index, T value)
{
array[index] = value;
}
}
class Tester
{
static void Main(string[] args)
{
//declaring an int array
MyGenericArray intArray = new MyGenericArray(5);
//setting values
for (int c = 0; c < 5; c++)
{
intArray
...
Write(intArray
...
WriteLine();
//declaring a character array
MyGenericArray charArray = new MyGenericArray(5);
//setting values
for (int c = 0; c < 5; c++)
{
charArray
...
Write(charArray
...
WriteLine();
Console
...




You can create generic collection classes
...
NET Framework class library contains several new generic
collection classes in the System
...
Generic namespace
...
Collectionsnamespace
...




You may create generic classes constrained to enable access to methods on particular data types
...


Generic Methods
In the previous example, we have used a generic class; we can declare a generic method with a type parameter
...
Collections
...
WriteLine("Int values before calling swap:");
Console
...
WriteLine("Char values before calling swap:");
Console
...
WriteLine("Int values after calling swap:");
Console
...
WriteLine("Char values after calling swap:");
Console
...
ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Int values before calling swap:
a = 10, b = 20
Char values before calling swap:
c = I, d = V
Int values after calling swap:
a = 20, b = 10
Char values after calling swap:
c = V, d = I

Generic Delegates
You can define a generic delegate with type parameters
...
Collections
...
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

TUTORIALS POINT
Simply Easy Learning

CHAPTER

37
C# Anonymous Methods

W

e 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);
};
//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
...


The unsafe code or the unmanaged code is a code block that uses a pointer variable
...
e
...

Like any variable or constant, you must declare a pointer before you can use it to store any variable address
...
WriteLine("Data is: {0} ",

TUTORIALS POINT
Simply Easy Learning

var);

Console
...
ReadKey();
}
}
}
When the above code wass compiled and executed, it produces the following result:
Data is: 20
Address is: 99215364
Instead of declaring an entire method as unsafe, you can also declare a part of the code as unsafe
...


Retrieving the Data Value Using a Pointer
You can retrieve the data stored at the located referenced by the pointer variable, using the ToString()method
...
WriteLine("Data is: {0} " , var);
Console
...
WriteLine("Address is: {0} " , (int)p);
}
Console
...
The following example illustrates this:
using System;
namespace UnsafeCodeApplication
{
class TestPointer
{
public unsafe void swap(int* p, int *q)
{
int temp = *p;
*p = *q;
*q = temp;
}

public unsafe static void Main()
{
TestPointer p = new TestPointer();
int var1 = 10;
int var2 = 20;
int* x = &var1;
int* y = &var2;

Console
...
swap(x, y);

Console
...
ReadKey();
}
}
}

TUTORIALS POINT
Simply Easy Learning

When the above code is compiled and executed, it produces the following result:
Before Swap: var1: 10, var2: 20
After Swap: var1: 20, var2: 10

Accessing Array Elements Using a Pointer
In C#, an array name and a pointer to a data type same as the array data, are not the same variable type
...
You can increment the pointer variable p because it is not fixed in memory but
an array address is fixed in memory, and you can't increment that
...

The following example demonstrates this:
using System;
namespace UnsafeCodeApplication
{
class TestPointer
{
public unsafe static void Main()
{
int[]

list = {10, 100, 200};

fixed(int *ptr = list)

/* let us have array address in pointer */
for ( int i = 0; i < 3; i++)
{
Console
...
WriteLine("Value of list[{0}]={1}", i, *(ptr + i));
}
Console
...

For example, to compile a program named prog1
...
cs
If you are using Visual Studio IDE then you need to enable use of unsafe code in the project properties
...

Click on the Build tab
...


TUTORIALS POINT
Simply Easy Learning

CHAPTER

39
C# 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 have written 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 has not
been called
...

The Not Runnable State: a thread is not runnable, 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 has completed execution or has been aborted
...
Threading
...
It allows creating and accessing
individual threads in a multithreaded application
...


TUTORIALS POINT
Simply Easy Learning

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:
S
...
Calling this method usually terminates the thread
...
For better performance, use fields that are marked with the
ThreadStaticAttribute attribute instead
...
For better performance, use fields that are marked with the
ThreadStaticAttribute attribute instead
...


5

public static void BeginThreadAffinity()
Notifies a host that managed code is about to execute instructions that depend on the identity of the current
physical operating system thread
...


7

public static void EndThreadAffinity()
Notifies a host that managed code has finished executing instructions that depend on the identity of the current
physical operating system thread
...
For better performance,
use fields that are marked with the ThreadStaticAttribute attribute instead
...
For
better performance, use fields that are marked with the ThreadStaticAttribute attribute instead
...


11

public static AppDomain GetDomain()
Returns a unique application domain identifier

12

public static LocalDataStoreSlot GetNamedDataSlot( string name )
Looks up a named data slot
...


13

public void Interrupt()
Interrupts a thread that is in the WaitSleepJoin thread state
...
This method has different overloaded forms
...

16

public static void ResetAbort()
Cancels an Abort requested for the current thread
...
For better
performance, use fields marked with the ThreadStaticAttribute attribute instead
...


19

public static void Sleep( int millisecondsTimeout )
Makes the thread pause for a period of time
...
The value is the latest written by any processor in a computer, regardless of the
number of processors or the state of processor cache
...
Only some
are given above
...
This method
has different overloaded forms
...


23

public static bool Yield()
Causes the calling thread to yield execution to another thread that is ready to run on the current processor
...


Creating Threads
Threads are created by extending the Thread class
...

The following program demonstrates the concept:
using System;
using System
...
WriteLine("Child thread starts");
}
static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);

TUTORIALS POINT
Simply Easy Learning

Console
...
Start();
Console
...

The following example demonstrates the use of the sleep() method for making a thread pause for a specific period of
time
...
Threading;
namespace MultithreadingApplication
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
Console
...
WriteLine("Child Thread Paused for {0} seconds",
sleepfor / 1000);
Thread
...
WriteLine("Child thread resumes");
}
static void Main(string[] args)
{
ThreadStart childref = new ThreadStart(CallToChildThread);
Console
...
Start();
Console
...

The runtime aborts the thread by throwing a ThreadAbortException
...

The following program illustrates this:
using System;
using System
...
WriteLine("Child thread starts");
// do some work, like counting to 10
for (int counter = 0; counter <= 10; counter++)
{
Thread
...
WriteLine(counter);
}
Console
...
WriteLine("Thread Abort Exception");
}
finally
{
Console
...
WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread
...
Sleep(2000);
//now abort the child
Console
...
Abort();
Console
Title: C# notes
Description: it is given C# notes with best descibe which you can understand easily.