0% found this document useful (0 votes)
17 views

Unit 2

The document discusses object oriented programming concepts like encapsulation, polymorphism and inheritance in C#. It then describes various data types in C# like boolean, integral, floating point, decimal and string types. It also discusses variables, variable definition, initialization and accepting input from the user.

Uploaded by

rajeshcse2020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Unit 2

The document discusses object oriented programming concepts like encapsulation, polymorphism and inheritance in C#. It then describes various data types in C# like boolean, integral, floating point, decimal and string types. It also discusses variables, variable definition, initialization and accepting input from the user.

Uploaded by

rajeshcse2020
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 64

MANAKULA VINAYAGAR INSTITUTE OF TECHNOLOGY

Kalitheerthalkuppam, Puducherry – 605107.


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
CS T73 PLATFORM TECHNOLOGY

UNIT – II
.NET Languages: C# Language Fundamentals – Classes and Objects – Methods – Fields and
Properties - Inheritance and Polymorphism – Operator Overloading – Struts - Interfaces –
Arrays – Indexers and Collections – Strings and Regular Expressions – Handling Exceptions
– Delegates and Events.

CONCEPT OF OOPS

At the center of C# is object-oriented programming (OOP). The object-oriented methodology


is inseparable from C#, and all C# programs are to at least some extent object oriented. C#’s
basic unit of encapsulation is the class. A

defines the form of an object. It specifies both the data and the code that will operate on that
data. C# uses a class specification to construct objects. Objects are instances of a class. Thus, a
class is essentially a set of plans that specify how to build an object. Collectively, the code and
data that constitute a class are called its members. Method is C#’s term for a subroutine. Thus,
the methods of a class contain code that acts on the fields defined by that class.

To support the principles of object-oriented programming, all OOP languages, including C#,
have three traits in common: encapsulation, polymorphism, and inheritance.

2.1.1 Object oriented programming

 Encapsulation
Encapsulation is a programming mechanism that binds together code and the data. In an
objectoriented language, code and data can be bound together in such a way that an
object is created.

 Polymorphism
Concept of polymorphism is often expressed by the phrase “one interface, multiple
methods.” This means that it is possible to design a generic interface to a group of related
activities.

 Inheritance
Inheritance is the process by which one object can acquire the properties of another
object.

CS T73 PLATFORM TECHNOLOGY Page 1


1. Write about the Types and Variables

DATA TYPES

C# contains two general categories of built-in data types: value types and reference types. For
a value type, a variable holds an actual value, such 3.1416 or 212. For a reference type, a
variable holds a reference to the value. The most commonly used reference type is the class. The
value types are described here.

The Boolean Type

Boolean types are declared using the keyword, bool. They have two values: true or false. In
other languages, such as C and C++, boolean conditions can be satisfied where 0 means false and
anything else means true. However, in C# the only values that satisfy a boolean condition is true
and false, which are official keywords. Listing 2-1 shows one of many ways that boolean types
can be used in a program.

Displaying Boolean Values: Boolean.cs


using System;
class Booleans
{ public static void Main()
{ bool content = true;
bool noContent = false;
Console.WriteLine("It is {0} that C# Station provides C# programming language content.",
content);
Console.WriteLine("The statement above is not {0}.", noContent);
}
}

In the above example the boolean values are written to the console as a part of a sentence. The
only legal values for the bool type are either true or false, as shown by the assignment of true to
content and false to noContent. When run, this program produces the following output:

It is True that C# Station provides C# programming language content.

The statement above is not False.

Integral Types

In C#, an integral is a category of types. For anyone confused because the word Integral
sounds like a mathematical term, from the perspective of C# programming, these are actually
defined as Integral types in the C# programming language specification. They are whole
numbers, either signed or unsigned, and the char type. The char type is a Unicode character, as

CS T73 PLATFORM TECHNOLOGY Page 2


defined by the Unicode Standard. For more information, visit The Unicode Home Page. table 2-1
shows the integral types, their size, and range.

Table 2.1 Integral types

Integral types are well suited for those operations involving whole number calculations.
The char type is the exception, representing a single Unicode character. As you can see from the
table above, you have a wide range of options to choose from, depending on your requirements.

Floating Point and Decimal Types

A C# floating point type is either a float or double. They are used any time you need to
represent a real number, as defined by IEEE 754. For more information on IEEE 754, visit the
IEEE Web Site. Decimal types should be used when representing financial or money values.
table 2-2 shows the floating point and decimal types, their size, precision, and range.

Table 2.2 floating point types

Floating point types are used when you need to perform operations requiring fractional
representations. However, for financial calculations, the decimal type is the best choice because
you can avoid rounding errors.

// Find the radius of a circle given its area.


using System;

CS T73 PLATFORM TECHNOLOGY Page 3


class FindRadius {
static void Main() {
Double r;
Double area;
area = 10.0;

r = Math.Sqrt(area / 3.1416);
Console.WriteLine("Radius is " + r);
}}
The output from the program is shown here:
Radius is 1.78412203012729

The string Type

A string is a sequence of text characters. You typically create a string with a string literal,
enclosed in quotes: "This is an example of a string." You've seen strings being used in Lesson 1,
where we used the Console.WriteLine method to send output to the console. Some characters
aren't printable, but you still need to use them in strings. Therefore, C# has a special syntax
where characters can be escaped to represent non-printable characters. For example, it is
common to use newlines in text, which is represented by the '\n' char. The backslash, '\',
represents the escape. When preceded by the escape character, the 'n' is no longer interpreted as
an alphabetical character, but now represents a newline.

We have to escape that too by typing two backslashes, as in '\\'. table 2-3 shows a list of
common escape sequences

Table 2.3 String types

CS T73 PLATFORM TECHNOLOGY Page 4


Another useful feature of C# strings is the verbatim literal, which is a string with a @
symbol prefix, as in @"Some string". Verbatim literals make escape sequences translate as
normal characters to enhance readability. To appreciate the value of verbatim literals, consider a
path statement such as "c:\\topdir\\subdir\\subdir\\myapp.exe". As you can see, the backslashes
are escaped, causing the string to be less readable. You can improve the string with a verbatim
literal, like this: @"c:\topdir\subdir\subdir\myapp.exe".

VARIABLES

A variable is nothing but a name given to a storage area that our programs can manipulate. 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:

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. For this chapter, let us study only basic
variable types.

Variable Definition in C#

Syntax for variable definition in C# is:


<data_type> <variable_list>;
Here, data_type must be a valid C# data type including char, int, float, double, or any user-
defined data type, etc., and variable_list may consist of one or more identifier names separated
by commas.
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:
int i = 100;

CS T73 PLATFORM TECHNOLOGY Page 5


Variable Initialization in C#

Variables are initialized (assigned a value) with an equal sign followed by a constant expression.

The general form of initialization is:


variable_name = value;
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists
of an equal sign followed by a constant expression as:
<data_type> <variable_name> = value;

Some examples are:


int d = 3, f = 5; /* initializing d and f. */
byte z = 22; /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x'; /* the variable x has the value 'x'. */

It is a good programming practice to initialize variables properly, otherwise sometimes program


would produce unexpected result.

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.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
a = 10, b = 20, c = 30
CS T73 PLATFORM TECHNOLOGY Page 6
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.
For example,
int num;
num = Convert.ToInt32(Console.ReadLine());
The function Convert.ToInt32() converts the data entered by the user to int data type, because
Console.ReadLine() accepts the data in string format.
Lvalues and Rvalues in C#:
There are two kinds of expressions in C#:
lvalue: An expression that is an lvalue may appear as either the left-hand or right-hand side of an
assignment.
rvalue: An expression that is an rvalue may appear on the right- but not left-hand side of an
assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals
are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a
valid statement:
int g = 20;
But following is not a valid statement and would generate compile-time error:
10 = 20;

2.Write about operators in c#

Operators in C#

An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C# is rich in built-in operators and provides the following type of operators:

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators

This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other
operators one by one.

CS T73 PLATFORM TECHNOLOGY Page 7


Arithmetic Operators

Following table shows all the arithmetic operators supported by C#. Assume variable A holds 10
and variable B holds 20 then:

EXAMPLE

using System;
namespace OperatorsAppl
{
class Program
{
static void Main(string[] args)
{
int a = 21;
int b = 10;
int c;
c = a + b;
Console.WriteLine("Line 1 - Value of c is {0}", c);
c = a - b;
Console.WriteLine("Line 2 - Value of c is {0}", c);
c = a * b;
Console.WriteLine("Line 3 - Value of c is {0}", c);
c = a / b;
Console.WriteLine("Line 4 - Value of c is {0}", c);
c = a % b;
Console.WriteLine("Line 5 - Value of c is {0}", c);
c = a++;
Console.WriteLine("Line 6 - Value of c is {0}", c);
c = a--;
Console.WriteLine("Line 7 - Value of c is {0}", c);
Console.ReadLine();

CS T73 PLATFORM TECHNOLOGY Page 8


}
}
}

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

OUTPUT
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22

Relational Operators

Following table shows all the relational operators supported by C#. Assume variable A holds 10
and variable B holds 20, then:

CS T73 PLATFORM TECHNOLOGY Page 9


EXAMPLE
using System;

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

if (a == b)
{
Console.WriteLine("Line 1 - a is equal to b");
}
else
{
Console.WriteLine("Line 1 - a is not equal to b");
}
if (a < b)
{
Console.WriteLine("Line 2 - a is less than b");
}
else
{
Console.WriteLine("Line 2 - a is not less than b");
}
if (a > b)
{
Console.WriteLine("Line 3 - a is greater than b");
}
else
{
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 4 - a is either less than or equal to b");
}
CS T73 PLATFORM TECHNOLOGY Page 10
if (b >= a)
{
Console.WriteLine("Line 5-b is either greater than or equal to b");
}
}
}

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

OUTPUT
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b

Logical Operators

Following table shows all the logical operators supported by C#. Assume variable A holds
Boolean value true and variable B holds Boolean value false, then:

EXAMPLE
using System;
namespace OperatorsAppl
{
class Program
{
static void Main(string[] args)
CS T73 PLATFORM TECHNOLOGY Page 11
{
bool a = true;
bool b = true;

if (a && b)
{
Console.WriteLine("Line 1 - Condition is true");
}
if (a || b)
{
Console.WriteLine("Line 2 - Condition is true");
}
/* lets change the value of a and b */
a = false;
b = true;
if (a && b)
{
Console.WriteLine("Line 3 - Condition is true");
}
else
{
Console.WriteLine("Line 3 - Condition is not true");
}
if (!(a && b))
{
Console.WriteLine("Line 4 - Condition is true");
}
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
OUTPUT
Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true

Bitwise Operators

Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^
are as follows:

CS T73 PLATFORM TECHNOLOGY Page 12


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. Assume variable A holds
60 and variable B holds 13 then:

CS T73 PLATFORM TECHNOLOGY Page 13


EXAMPLE

using System;
namespace OperatorsAppl
{
class Program
{
static void Main(string[] args)
{
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;

c = a & b; /* 12 = 0000 1100 */


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

c = a | b; /* 61 = 0011 1101 */
Console.WriteLine("Line 2 - Value of c is {0}", c);

c = a ^ b; /* 49 = 0011 0001 */
Console.WriteLine("Line 3 - Value of c is {0}", c);

c = ~a; /*-61 = 1100 0011 */


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

c = a << 2; /* 240 = 1111 0000 */


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

CS T73 PLATFORM TECHNOLOGY Page 14


c = a >> 2; /* 15 = 0000 1111 */
Console.WriteLine("Line 6 - Value of c is {0}", c);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:

OUTPUT
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

Assignment Operators

There are following assignment operators supported by C#:

EXAMPLE
using System;

CS T73 PLATFORM TECHNOLOGY Page 15


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

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

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

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

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

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

c = 200;
c %= a;
Console.WriteLine("Line 6 - %= Value of c = {0}", c);

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

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

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

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

c |= 2;
Console.WriteLine("Line 11 - |= Value of c = {0}", c);
Console.ReadLine();
}
}
}

CS T73 PLATFORM TECHNOLOGY Page 16


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

OUTPUT
Line 1 - = Value of c = 21
Line 2 - += Value of c = 42
Line 3 - -= Value of c = 21
Line 4 - *= Value of c = 441
Line 5 - /= Value of c = 21
Line 6 - %= Value of c = 11
Line 7 - <<= Value of c = 44
Line 8 - >>= Value of c = 11
Line 9 - &= Value of c = 2
Line 10 - ^= Value of c = 0
Line 11 - |= Value of c = 2

Misc Operators

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

EXAMPLE

using System;

namespace OperatorsAppl
{

class Program
{

CS T73 PLATFORM TECHNOLOGY Page 17


static void Main(string[] args)
{

/* example of sizeof operator */


Console.WriteLine("The size of int is {0}", sizeof(int));
Console.WriteLine("The size of short is {0}", sizeof(short));
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);

b = (a == 10) ? 20 : 30;
Console.WriteLine("Value of b is {0}", b);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
OUTPUT
The size of int is 4
The size of short is 2
The size of double is 8
Value of b is 30
Value of b is 20

3. What are the Control Statements in C#?Explain with appropriate examples.


(OR)
Explain about the Control Statements with example

Control Statements –Selection

There are three categories of program control statements: selection statements, which are the
if and the switch iteration statements, which consist of the for, while, do-while, and foreach
loops; and jump statements, which include break, continue, goto, return, and throw

 If Statement
 Switch Statement
 Break Statement
 Goto Statement

The if Statement

CS T73 PLATFORM TECHNOLOGY Page 18


An if statement allows you to take different paths of logic, depending on a given condition.
When the condition evaluates to a boolean true, a block of code for that true condition will
execute. You have the option of a single if statement, multiple else if statements, and an optional
else statement.

using System;

class IfSelect

{ public static void Main()

{ string myInput;

int myInt;

Console.Write("Please enter a number: ");

myInput = Console.ReadLine();

myInt = Int32.Parse(myInput);

// Single Decision and Action with braces

if (myInt > 0)

{ Console.WriteLine("Your number {0} is greater than zero.", myInt); }

// Single Decision and Action without brackets

if (myInt < 0)

Console.WriteLine("Your number {0} is less than zero.", myInt);

// Either/Or Decision

if (myInt != 0)

{ Console.WriteLine("Your number {0} is not equal to zero.", myInt); } else

{ Console.WriteLine("Your number {0} is equal to zero.", myInt);

} // Multiple Case Decision

CS T73 PLATFORM TECHNOLOGY Page 19


if (myInt < 0 || myInt == 0)

{ Console.WriteLine("Your number {0} is less than or equal to zero.", myInt);

} else if (myInt > 0 && myInt <= 10)

{ Console.WriteLine("Your number {0} is in the range from 1 to 10.", myInt);

} else if (myInt > 10 && myInt <= 20)

{ Console.WriteLine("Your number {0} is in the range from 11 to 20.", myInt);

} else if (myInt > 20 && myInt <= 30)

{ Console.WriteLine("Your number {0} is in the range from 21 to 30.", myInt);

} else

{ Console.WriteLine("Your number {0} is greater than 30.", myInt);

The switch Statement

Another form of selection statement is the switch statement, which executes a set of logic
depending on the value of a given parameter. The types of the values a switch statement operates
on can be booleans, enums, integral types, and strings.

using System;

class SwitchSelect

public static void Main()

string myInput;

CS T73 PLATFORM TECHNOLOGY Page 20


int myInt;

begin:

Console.Write("Please enter a number between 1 and 3: ");

myInput = Console.ReadLine();

myInt = Int32.Parse(myInput);

// switch with integer type

switch (myInt)

{ case 1:

Console.WriteLine("Your number is {0}.", myInt);

break;

case 2: Console.WriteLine("Your number is {0}.", myInt);

break;

case 3:

Console.WriteLine("Your number is {0}.", myInt);

break;

default:

Console.WriteLine("Your number {0} is not between 1 and 3.", myInt);

break; }

decide:

Console.Write ("Type \"continue\" to go on or \"quit\" to stop: ");

myInput = Console.ReadLine();

// switch with string type

CS T73 PLATFORM TECHNOLOGY Page 21


switch (myInput)

{ case "continue":

goto begin;

case "quit":

Console.WriteLine("Bye.");

break;

default:

Console.WriteLine("Your input {0} is incorrect.", myInput);

goto decide;

} } }

2.1.5 Control Statements - Loops

• While loop.
• Do loop.
• For loop.
• Foreach loop.

The while Loop


A while loop will check a condition and then continues to execute a block of code as long
as the condition evaluates to a boolean value of true. Its syntax is as follows: while (<boolean
expression>) { <statements> }. The statements can be any valid C# statements. The boolean
expression is evaluated before any code in the following block has executed. When the boolean
expression evaluates to true, the statements will execute. Once the statements have executed,
control returns to the beginning of the while loop to check the boolean expression again.

When the boolean expression evaluates to false, the while loop statements are skipped and
execution begins after the closing brace of that block of code. Before entering the loop, ensure
that variables evaluated in the loop condition are set to an initial state. During execution, make
sure you update variables associated with the boolean expression so that the loop will end when
you want it to.

using System;

CS T73 PLATFORM TECHNOLOGY Page 22


class WhileLoop

public static void Main()

{ int myInt = 0;

while (myInt < 10)

{ Console.Write("{0} ", myInt);

myInt++;

} Console.WriteLine();

} }

The do Loop

A do loop is similar to the while loop, except that it checks its condition at the end of the
loop. This means that the do loop is guaranteed to execute at least one time. On the other hand, a
while loop evaluates its boolean expression at the beginning and there is generally no guarantee
that the statements inside the loop will be executed, unless you program the code to explicitly do
so. One reason you may want to use a do loop instead of a while loop is to present a message.

using System;
class DoLoop
{ public static void Main()
{ string myChoice;
do
{ // Print A Menu
Console.WriteLine("My Address Book\n");
Console.WriteLine("A - Add New Address");
Console.WriteLine("D - Delete Address");
Console.WriteLine("M - Modify Address");
Console.WriteLine("V - View Addresses");
Console.WriteLine("Q - Quit\n");
Console.WriteLine("Choice (A,D,M,V,or Q): ");
// Retrieve the user's choice
myChoice = Console.ReadLine();
// Make a decision based on the user's choice

CS T73 PLATFORM TECHNOLOGY Page 23


switch(myChoice)
{ case "A":
case "a":
Console.WriteLine("You wish to add an address.");
break;
case "D":
case "d":
Console.WriteLine("You wish to delete an address.");
break;
case "M":
case "m":
Console.WriteLine("You wish to modify an address.");
break;
case "V":
case "v":
Console.WriteLine("You wish to view the address list.");
break;
case "Q":case "q":
Console.WriteLine("Bye.");
break;
default:
Console.WriteLine("{0} is not a valid choice", myChoice);
break;
}
// Pause to allow the user to see the results
Console.Write("press Enter key to continue...");
Console.ReadLine();
Console.WriteLine();
} while (myChoice != "Q" && myChoice != "q"); // Keep going until the user wants to
quit
} }
The for Loop
A for loop works like a while loop, except that the syntax of the for loop includes
initialization and condition modification. for loops are appropriate when you know exactly how
many times you want to perform the statements within the loop. The contents within the for loop
parentheses hold three sections separated by semicolons (<initializer list>; <boolean
expression>; <iterator list>) { <statements> }. The initializer list is a comma separated list of
expressions. These expressions are evaluated only once during the lifetime of the for loop. This
is a one-time operation, before loop execution. This section is commonly used to initialize an
integer to be used as a counter.

CS T73 PLATFORM TECHNOLOGY Page 24


Once the initializer list has been evaluated, the for loop gives control to its second section,
the boolean expression. There is only one boolean expression, but it can be as complicated as
you like as long as the result evaluates to true or false. The boolean expression is commonly used
to verify the status of a counter variable.

When the boolean expression evaluates to true, the statements within the curly braces of the
for loop are executed. After executing for loop statements, control moves to the top of loop and
executes the iterator list, which is normally used to increment or decrement a counter. The
iterator list can contain a comma separated list of statements, but is generally only one statement.

using System;
class ForLoop
{
public static void Main()
{ for (int i=0; i < 20; i++)
{ if (i == 10)
break;
if (i % 2 == 0)
continue;
Console.Write("{0} ", i);
} Console.WriteLine();
}
}
The foreach Loop
A foreach loop is used to iterate through the items in a list. It operates on arrays or
collections such as ArrayList, which can be found in the System.Collections namespace. The
syntax of a foreach loop is foreach (<type> <iteration variable> in <list>) { <statements> }. The
type is the type of item contained in the list. For example, if the type of the list was int[] then the
type would be int.

The iteration variable is an identifier that you choose, which could be anything but should be
meaningful. For example, if the list contained an array of people's ages, then a meaningful name
for item name would be age. The in keyword is required.

using System;
class ForEachLoop
{
public static void Main()
{
string[] names = {"Cheryl", "Joe", "Matt", "Robert"};
foreach (string person in names)
{
CS T73 PLATFORM TECHNOLOGY Page 25
Console.WriteLine("{0} ", person);
}
}

Loop Control Statements:

Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed.

C# provides the following control statements. Click the following links to check their details.

EXAMPLE OF BREAK
using System;

namespace Loops
{

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

/* while loop execution */


while (a < 20)
{
Console.WriteLine("value of a: {0}", a);
a++;
if (a > 15)
{
/* terminate the loop using break statement */
break;
}
}

CS T73 PLATFORM TECHNOLOGY Page 26


Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15

EXAMPLE OF CONTINUE
using System;

namespace Loops
{

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

/* do loop execution */
do
{
if (a == 15)
{
/* skip the iteration */
a = a + 1;
continue;
}
Console.WriteLine("value of a: {0}", a);
a++;

} while (a < 20);

Console.ReadLine();
}
CS T73 PLATFORM TECHNOLOGY Page 27
}
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

GOTO STATEMENT
The goto statement is a jump statement that controls the execution of the program to another
segment of the same program. You create label at anywhere in program then can pass the
execution control via the goto statements.
using System;

namespace goto_statement
{
class Program
{
static void Main(string[] args)
{
string name;

label: //creating label with colon(:)

Console.WriteLine("Enter your name:");


name = Console.ReadLine();

Console.WriteLine("Welcome {0}", name);

goto label; //jump to label statement


}
}
}
note: To terminate the program press Ctrl+C

CS T73 PLATFORM TECHNOLOGY Page 28


POLYMORPHISM
 Polymorphism is one of the primary characteristics of Object Oriented Programming.
 “Poly” means “many” and “morph” means “form”.
 Thus polymorphism refers to being able to use many form of a type without regard to the
details.
 Types of Polymorphism
 Compile Time Polymorphism.
 Runtime Polymorphism.
Compile Time Polymorphism
 Compile time Polymorphism also known as Method Overloading.
 Method Overloading means having two or more methods with the same name but with
different parameters.
 It is also called as static polymorphism.
 Which method is to be called is decided at the compile time only.
 In static Polymorphism decision is taken at the Compile time.

EXAMPLE
using System;
namespace PolymorphismApplication
{
class Printdata
{
void print(int i)
{
Console.WriteLine("Printing int: {0}", i );
}

void print(double f)
{
Console.WriteLine("Printing float: {0}" , f);
}

CS T73 PLATFORM TECHNOLOGY Page 29


void print(string s)
{
Console.WriteLine("Printing string: {0}", s);
}

Void print(int a,float b)


{
Console.WriteLine("Printing int:{0}" , a);
Console.WriteLine("Printing float:{0}" , b);

Public static void Main(string[] args)


{
Printdata p = new Printdata();
// Call print to print integer
p.print(5);
// Call print to print float
p.print(500.263);
// Call print to print string
p.print("Hello C++");
p.print(12.12.0);
Console.ReadKey();

}
}
}

When the above code is compiled and executed, it produces the following result:
Printing int: 5
Printing float: 500.263
Printing int: 12
Printing float: 12.0
Printing string: Hello C++

Runtime Polymorphism

 Run Time Polymorphism also known as Method Overriding.

 Method Overriding means having two or more methods with the same name, same
parameters but with different implementation.

 It is also called as Dynamic Polymorphism.

CS T73 PLATFORM TECHNOLOGY Page 30


 In this process, an overridden method is called through reference variable of a superclass;
the determination of the method to be called is based on the object being referred to by
reference variable.

 The parent class uses the same virtual keyword. Every class that overrides the virtual
method will use the override keyword.
EXAMPLE

using System;
class Parent
{
public virtual void show()

{
Console.WriteLine("Parent");
}
}

class Child : Parent


{
public override void show()

{
Console.WriteLine("Child");
}
}
class grandchild : Parent
{
public override void show()

{
Console.WriteLine("grandChild");
}
}
class Test
{
static void Main()
{
Parent p = new Parent();
Parent c = new Child();
Parent g = new grandchild();

c.show();
p.show();
g.show();
Console.ReadLine();

CS T73 PLATFORM TECHNOLOGY Page 31


}
}

Output
Child
Parent
grandChild

INTERFACES
 An interface is defined as a syntactical contract that all the classes inheriting the interface
should follow.
 The interface defines the 'what' part of the syntactical contract and the deriving classes
define the 'how' part of the syntactical contract.
 Interfaces define properties, methods and events, which are the members of the interface.
Interfaces contain only the declaration of the members.
 It is the responsibility of the deriving class to define 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. It is similar to class declaration. Interface
statements are public by default. Following is an example of an interface declaration:

public interface ITransactions


{
// interface members
void showTransaction();
double getAmount();
}

EXAMPLE

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace InterfaceApplication
{

public interface ITransactions


{
// interface members
void showTransaction();
double getAmount();
}

CS T73 PLATFORM TECHNOLOGY Page 32


public class Transaction : ITransactions
{
private string tCode;
private string date;
private double amount;
public Transaction()
{
tCode = " ";
date = " ";
amount = 0.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("Transaction: {0}", tCode);
Console.WriteLine("Date: {0}", date);
Console.WriteLine("Amount: {0}", getAmount());

}
class Tester
{
static void Main(string[] args)
{
Transaction t1 = new Transaction("001", "8/10/2012", 78900.00);
Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);
t1.showTransaction();
t2.showTransaction();
Console.ReadKey();
}
}
}

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

Transaction: 001

CS T73 PLATFORM TECHNOLOGY Page 33


Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900

HANDLING EXCEPTION

An exception is a problem that arises during the execution of a program. 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.

Exceptions provide a way to transfer control from one part of a program to another. C# exception
handling is built upon four keywords: try, catch, finally and throw.
 try: A try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more catch blocks.
 catch: A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The catch keyword indicates the catching of an
exception.
 finally: The finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown. For example, if you open a file, it must be closed whether an
exception is raised or not.
 throw: A program throws an exception when a problem shows up. This is done using a
throw keyword.
Syntax
Assuming a block will raise and exception, a method catches an exception using a combination
of the try and catch keywords. A try/catch block is placed around the code that might generate an
exception. Code within a try/catch block is referred to as protected code, and the syntax for using
try/catch looks like the following:

try
{
// statements causing exception
}
catch( ExceptionName e1 )
{
// error handling code
}
catch( ExceptionName e2 )
{
// error handling code
}
catch( ExceptionName eN )
{
// error handling code

CS T73 PLATFORM TECHNOLOGY Page 34


}
finally
{
// statements to be executed
}

You can list down multiple catch statements to catch different type of exceptions in case your try
block raises more than one exception in different situations.

Exception Classes in C#
C# exceptions are represented by classes. The exception classes in C# are mainly directly or
indirectly derived from the System.Exception class. Some of the exception classes derived from
theSystem.Exceptionclassare
the System.ApplicationException and System.SystemException classes.
The System.ApplicationException class supports exceptions generated by application
programs. So the exceptions defined by the programmers should derive from this class.
The System.SystemException class is the base class for all predefined system exception.
The following table provides some of the predefined exception classes derived from the
Sytem.SystemException class:

Exception Class Description


System.IO.IOException Handles I/O errors.
Handles errors generated when a method
System.IndexOutOfRangeException
refers to an array index out of range.
Handles errors generated when type is
System.ArrayTypeMismatchException
mismatched with the array type.
Handles errors generated from deferencing a
System.NullReferenceException
null object.
Handles errors generated from dividing a
System.DivideByZeroException
dividend with zero.
System.InvalidCastException Handles errors generated during typecasting.
Handles errors generated from insufficient
System.OutOfMemoryException
free memory.
Handles errors generated from stack
System.StackOverflowException
overflow.

Handling Exceptions
C# provides a structured solution to the exception handling problems in the form of try and catch
blocks. Using these blocks the core program statements are separated from the error-handling
statements.
CS T73 PLATFORM TECHNOLOGY Page 35
These error handling blocks are implemented using the try, catch and finally keywords.

EXAMPLE

using System;
namespace ErrorHandlingApplication
{
class DivNumbers
{
int result;
DivNumbers()
{
result = 0;
}
public void division(int num1, int num2)
{
try
{
result = num1 / num2;
}
catch (DivideByZeroException e)
{
Console.WriteLine("Exception caught: {0}", e);
}
finally
{
Console.WriteLine("Result: {0}", result);
}

}
static void Main(string[] args)
{
DivNumbers d = new DivNumbers();
d.division(25, 0);
Console.ReadKey();
}
}
}

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

Exception caught: System.DivideByZeroException: Attempted to divide by zero.


at ...
Result: 0

CS T73 PLATFORM TECHNOLOGY Page 36


DELEGATES

C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference type


variable that holds the reference to a method. The reference can be changed at runtime.
Delegates are especially used for implementing events and the call-back methods. All delegates
are implicitly derived from the System.Delegate class.
Declaring Delegates
Delegate declaration determines the methods that can be referenced by the delegate. A delegate
can refer to a method, which have the same signature as that of 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.
Syntax for delegate declaration is:

delegate <return type> <delegate-name> <parameter list>

Instantiating Delegates
Once a delegate type has been declared, a delegate object must be created with the new keyword
and be associated with a particular method. When creating a delegate, the argument passed to
the newexpression is written like a method call, but without the arguments to the method. For
example:
public delegate void printString(string s);
...
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.

using System;

delegate int NumberChanger(int n);


namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
CS T73 PLATFORM TECHNOLOGY Page 37
}

public static int MultNum(int q)


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

static void Main(string[] args)


{
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
//calling the methods using the delegate objects
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}

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

Value of Num: 35
Value of Num: 175

1. INDEXERS AND PROPERTIES

PROPERTIES

Properties are named members of classes, structures, and interfaces. Member variables or
methods in a class or structures are called Fields. Properties are an extension of fields and are
accessed using the same syntax. They use accessors through which the values of the private
fields can be read, written or manipulated.
Properties do not name the storage locations. Instead, they have accessors that read, write, or
compute their values.
For example, let us have a class named Student, with private fields for age, name and code. We
cannot directly access these fields from outside the class scope, but we can have properties for
accessing these private fields.
CS T73 PLATFORM TECHNOLOGY Page 38
The accessor of a property contains the executable statements that helps in getting (reading or
computing) or setting (writing) the property. The accessor declarations can contain a get
accessor, a set accessor, or both.

General form of property

Type name

Get

Set

Type-specifies the data type of the property

Name specifies the property name

Get-gets the value of the variable

Set-sets the value of the variable and it has implicit variable called value that contains the value
to be assigned to the property.

EXAMPLE

using System;
class simpleprop
{
private int prop;
public simpleprop()
{
prop = 0;
}
public int myprop

CS T73 PLATFORM TECHNOLOGY Page 39


{
get
{
return prop;
}
set
{
if (value >= 0)
{
prop = value;
}
}
}
}
class propertydemo
{
public static void Main()
{
simpleprop ob=new simpleprop();
Console.WriteLine("ORIGINAL VALUE OF OB.MYPROP"+ob.myprop);
ob.myprop=100;
Console.WriteLine("value of prop"+ob.myprop);
ob.myprop=-10;
Console.WriteLine("value of prop after assigning negative value -10"+ob.myprop);
}
}

OUTPUT

ORIGINAL VALUE OF OB.MYPROP:0

Value of prop: 100

Value of prop after assigning negative value -10: 100

INDEXERS

An indexer allows an object to be indexed like an array. When you define an indexer for a class,
this class behaves like a virtual array. You can then access the instance of this class using the
array access operator ([ ]).

A one dimensional indexer has the following syntax:

element-type this[int index]


{
// The get accessor.
get

CS T73 PLATFORM TECHNOLOGY Page 40


{
// return the value specified by index
}

// The set accessor.


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

Here, element-type is the base type of the indexer. Thus, each element accessed by the indexer
will be of type element-type. The element type corresponds to the base type of an array. The
parameter index receives the index of the element being accessed. Except that it does not have a
return type or parameter declarations. The accessors are automatically called when the indexer is
used, and both accessors receive index as a parameter. If the indexer is on the left side of an
assignment statement, then the set accessor is called, and the element specified by index must be
set. Otherwise, the get accessor is called, and the value associated with index must be returned.
The set accessor also receives an implicit parameter called value, which contains the value being
assigned to the specified index.

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. A.";
}
public string this[int index]
{
get
{
string tmp;

if (index >= 0 && index <= size - 1)


{
tmp = namelist[index];
}
else

CS T73 PLATFORM TECHNOLOGY Page 41


{
tmp = "";
}

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

static void Main(string[] args)


{
IndexedNames names = new IndexedNames();
names[0] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";
names[4] = "Davinder";
names[5] = "Sunil";
names[6] = "Rubic";
for (int i = 0; i < IndexedNames.size; i++)
{
Console.WriteLine(names[i]);
}
Console.ReadKey();
}
}
}

OUTPUT

Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.

CS T73 PLATFORM TECHNOLOGY Page 42


ARRAYS
 An array is a collection of variables of same type that are referred by a common name.

 All arrays consist of contiguous memory locations. The lowest address corresponds to the
first element and the highest address to the last element.

Example:

We can use an array to hold a record of the dialy high temperature for a month,a list of stock
prices, employee details etc.

ONE DIMENSIONAL ARRAY

A one dimensional array is a list of related variables.

General form:

Type [] array-name=new type [size];

 Type declares the data type of an array.

 In c# the square bracket comes after type. Single square bracket indicates one-
dimensional array.

 The numbers of array elements are determined by size.

 Since arrays are implemented as objects, the creation of an array is a two-step process.

 Step 1: First declare array reference variable.

Example: int [] sample;

 Step 2: Allocate memory for the array, assigning a reference to that memory to the array
variable by using new operator.

Sample=new int [10];

ASSIGNING VALUES TO ARRAYS

1) We can assign values to individual array elements, by using the index number, like:

CS T73 PLATFORM TECHNOLOGY Page 43


double[] balance = new double[10];
balance[0] = 4500.0;
2) We can assign values to the array at the time of declaration, like:

double[] balance = { 2340.0, 4523.69, 3421.0};


3) We can also create and initialize an array, like:

int [] marks = new int[5] { 99, 98, 92, 97, 95};


4) In the preceding case, We may also omit the size of the array, like:

int [] marks = new int[] { 99, 98, 92, 97, 95};


5) We can also copy an array variable into another target array variable. In that case, both
the target and source would point to the same memory location:

int [] marks = new int[] { 99, 98, 92, 97, 95};


int[] score = marks;

EXAMPLE OF SINGLE-DIMENSIONAL ARRAY

using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int [] n = new int[10]; /* n is an array of 10 integers */
int i,j;

/* initialize elements of array n */


for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100;
}

/* output each array element's value */


for (j = 0; j < 10; j++ )
{
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
Console.ReadKey();
}
}
}

CS T73 PLATFORM TECHNOLOGY Page 44


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

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

1.4 MULTI-DIMENSIONAL ARRAY


A multi-dimensional array is an array that has two or more dimensions and an individual element
is accessed through the combination of two or more indices.

TWO-DIMENSIONAL ARRAYS
 The simplest form of the multidimensional array is the 2-dimensional array. A 2-
dimensional array is, in essence, a list of one-dimensional arrays.
 A 2-dimensional array can be thought of as a table, which will have x number of rows
and y number of columns. Following is a 2-dimentional array, which contains 3 rows and
4 columns:

 Thus, every element in array a is identified by an element name of the form a[ i , j ],


where a is the name of the array, and i and j are the subscripts that uniquely identify each
element in a.

DECLARATION

 To declare a two-dimensional integer array of size 10, 20 (i.e.) 10 rows and 20 columns,

Int [,] array_name = new int [10, 20];

 Note that the two-dimension arrays are separated from each other by a comma.

INITIALIZING TWO-DIMENSIONAL ARRAYS

CS T73 PLATFORM TECHNOLOGY Page 45


 Two dimensional arrays may be initialized by specifying bracketed values for each row.
Following is an array with 3 rows and each row has 4 columns.

int [,] a = int [3,4] = {


{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};

DECLARING ARRAY OF THREE OR MORE DIMENSIONS

Type [ ,…, ] array_name = new type[size1,size2,….size N];


EXAMPLE OF MULTI-DIMENSIONAL ARRAYS
using System;
class Program
{
static void Main(string[] args)
{
int t, i;
int [,] table = new int [3,4];
for (t = 0; t < 3; ++t)
{
for (i = 0; i < 4; i++)
{
table[t, i] = (t * 4) + i + 1;
Console.WriteLine(table[t, i] + " ");
}
}

}
}

OUTPUT (CONCEPTUAL VIEW)


0 1 2 3
0 1 2 3 4

1 5 6 7 8
9 10 11 12
2

JAGGED ARRAYS

A Jagged array is an array of arrays.

A jagged array is an array in which the length of each array can differ. Thus a jagged array can
be used to create a table in which the lengths of the rows are not the same.

CS T73 PLATFORM TECHNOLOGY Page 46


int [ ] [ ] x = new int [3] [ ];
x[0] = new int [3];
x[1] =new int [2];
x[2] =new int [4];

X[0][0] X[0][1] X[0][2]

X[1][0] X[1][1]

X[2][0] X[2][1] X[2][2] X[2][3]

EXAMPLE
using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
/* a jagged array of 5 array of integers*/
int[][] a = new int[][]{new int[]{0,0},new int[]{1,2},
new int[]{2,4},new int[]{ 3, 6 }, new int[]{ 4, 8 } };

int i, j;

/* output each array element's value */


for (i = 0; i < 5; i++)
{
for (j = 0; j <; 2; j++)
{
Console.WriteLine("a[{0}][{1}] = {2}", i, j, a[i][j]);
}
}
Console.ReadKey();
}
}
}

CS T73 PLATFORM TECHNOLOGY Page 47


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

a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

THE FOR EACH-LOOP

 The for each loop is used to cycle through the elements of a collection.
 A collection is a group of objects.
 C# defines several types of collections, of which one is an array.
 The general form of for each loop:
Foreach(type var_name in collection)
{
Statements;
}
 The type specifies the data type and var_name specuies the name of the iteration variable.
 Collections specifies the array.
 The array type and iteration variable type should be same.
 The iteration variable is read only and hence we cannot change the contents of the array
by assigning new value to iteration variable.
EXAMPLE
using System;
class Program
{
static void Main(string[] args)
{
int sum = 0;
int[] nums = new int[10];
for (int i = 0; i < 10; i++)
{
nums[i] = i;
}
foreach (int x in nums)
{
Console.WriteLine("Vaue is:" + x);

CS T73 PLATFORM TECHNOLOGY Page 48


sum += x;
}
Console.WriteLine("Summation:" + sum);
}
}

OUTPUT

Value is : 0
Value is : 1
Value is : 2
Value is : 3
Value is : 4
Value is : 5
Value is : 6
Value is : 7
Value is : 8
Value is : 9
Sumation : 45

STRINGS

 From a day-to-day programming standpoint, one of the most important of C#’s data types
is string.
 string defines and supports character strings. In many other programming languages a
string is an array of characters.
 This is not the case with C#. In C#, strings are objects. Thus, string is a reference type.
For example, in the statement
Console.WriteLine("In C#, strings are objects.");
 The string “In C#, strings are objects.” is automatically made into a string object by C#.

Constructing Strings
 The easiest way to construct a string is to use a string literal.
 For example, here str is a string reference variable that is assigned a reference to a string
literal: string str = "C# strings are powerful.";
 In this case, str is initialized to the character sequence “C# strings are powerful.”
 You can also create a string from a char array. For example:

using System;
class StringDemo {
public static void Main() {
char[] charray = {'A', ' ', 's', 't', 'r', 'i', 'n', 'g', '.' };
string str1 = new string(charray);
string str2 = "Another string.";
CS T73 PLATFORM TECHNOLOGY Page 49
Console.WriteLine(str1);
Console.WriteLine(str2);
}
}
The output from the program is shown here:
A string.
Another string.

Operating on Strings
The string class contains several methods that operate on strings. Table 7-1 shows a few.
The string type also includes the Length property, which contains the length of the string. To
obtain the value of an individual character of a string, you simply use an index. For example:
string str = "test";
Console.WriteLine(str[0]);
This displays “t”, the first character of “test”. Like arrays, string indexes begin at zero.
One important point, however, is that you cannot assign a new value to a character within a
string using an index. An index can only be used to obtain a character.

Here is a program that demonstrates several string operations:


// Some string operations.
using System;
class StrOps {
public static void Main() {
string str1 =
"When it comes to .NET programming, C# is #1.";
string str2 = string.Copy(str1);
string str3 = "C# strings are powerful.";
string strUp, strLow;
int result, idx;

CS T73 PLATFORM TECHNOLOGY Page 50


Console.WriteLine("str1: " + str1);
Console.WriteLine("Length of str1: " +
str1.Length);
// create upper- and lowercase versions of str1
strLow = str1.ToLower();
strUp = str1.ToUpper();
Console.WriteLine("Lowercase version of str1:\n " +
strLow);
Console.WriteLine("Uppercase version of str1:\n " +
strUp);
Console.WriteLine();
// display str1, one char at a time.
Console.WriteLine("Display str1, one char at a time.");
for(int i=0; i < str1.Length; i++)
Console.Write(str1[i]);
Console.WriteLine("\n");
// compare strings
if(str1 == str2)
Console.WriteLine("str1 == str2");
else
Console.WriteLine("str1 != str2");
if(str1 == str3)
Console.WriteLine("str1 == str3");
else
Console.WriteLine("str1 != str3");
result = str1.CompareTo(str3);
if(result == 0)
Console.WriteLine("str1 and str3 are equal");
else if(result < 0)
Console.WriteLine("str1 is less than str3");
else
Console.WriteLine("str1 is greater than str3");
Console.WriteLine();
// assign a new string to str2
str2 = "One Two Three One";
// search string
idx = str2.IndexOf("One");
Console.WriteLine("Index of first occurrence of One: " + idx);
idx = str2.LastIndexOf("One");
Console.WriteLine("Index of last occurrence of One: " + idx);
}
}
This program generates the following output:
str1: When it comes to .NET programming, C# is #1.
Length of str1: 44
Lowercase version of str1:
when it comes to .net programming, c# is #1.
CS T73 PLATFORM TECHNOLOGY Page 51
Uppercase version of str1:
WHEN IT COMES TO .NET PROGRAMMING, C# IS #1.
Display str1, one char at a time.
When it comes to .NET programming, C# is #1.
str1 == str2
str1 != str3
str1 is greater than str3
Index of first occurrence of One: 0
Index of last occurrence of One: 14

You can concatenate (join together) two strings using the + operator. For example, this
statement:
string str1 = "One";
string str2 = "Two";
string str3 = "Three";
string str4 = str1 + str2 + str3;
initializes str4 with the string “OneTwoThree”.

Arrays of Strings
Like any other data type, strings can be assembled into arrays. For example:
// Demonstrate string arrays.
using System;
class StringArrays {
public static void Main() {
string[] str = { "This", "is", "a", "test." };
Console.WriteLine("Original array: ");
for(int i=0; i < str.Length; i++)
Console.Write(str[i] + " ");
Console.WriteLine("\n");
// change a string
str[1] = "was";
str[3] = "test, too!";
Console.WriteLine("Modified array: ");
for(int i=0; i < str.Length; i++)
Console.Write(str[i] + " ");
}
}
Here is the output from this program:
Original array:
This is a test.
Modified array:
This was a test, too!

STRUCTURES

 Classes are reference types.

CS T73 PLATFORM TECHNOLOGY Page 52


 This means that class objects are accessed through a reference.
 This differs from the value types, which are accessed directly.
 However, sometimes it would be useful to be able to access an object directly, in the
 way that value types are.
 One reason for this is efficiency. Accessing class objects through a reference adds
overhead onto every access. It also consumes space.

SYNTAX
Structures are declared using the keyword struct and are syntactically similar to classes.
Here is the general form of a struct:
struct name : interfaces {
// member declarations
}
 Structures do not support inheritance; structure members cannot be specified as abstract,
virtual, or protected.
 A structure object can be created using new in the same way as a class object, but it is
not required. When new is used, the specified constructor is called. When new is not
used, the object is still created, but it is not initialized. Thus, you will need to perform
any initialization manually
// Demonstrate a structure.
using System;
// Define a structure.
struct Book {
public string author;
public string title;
public int copyright;
public Book(string a, string t, int c) {
author = a;
title = t;
copyright = c;
}
}

// Demonstrate Book structure.


class StructDemo {
public static void Main() {
Book book1 = new Book("Herb Schildt","C#: The Complete Reference", 2005); // explicit
constructor
Book book2; // no constructorPART I
Console.WriteLine(book1.title + " by " + book1.author + ", (c) " + book1.copyright);

CS T73 PLATFORM TECHNOLOGY Page 53


Console.WriteLine();
// Console.WriteLine(book2.title); // error, must initialize first
Book2.title = "Red Storm Rising";
Console.WriteLine(book3.title); // now OK
}
}

The output from this program is shown here:


C#: The Complete Reference by Herb Schildt, (c) 2005

Red Storm Rising

// Copy a struct.
using System;
// Define a structure.
struct MyStruct {
public int x;
}328 Part I: The C# Language
// Demonstrate structure assignment.
class StructAssignment {
public static void Main() {
MyStruct a;
MyStruct b;
a.x = 10;
b.x = 20;
Console.WriteLine("a.x {0}, b.x {1}", a.x, b.x);
a = b;
b.x = 30;
Console.WriteLine("a.x {0}, b.x {1}", a.x, b.x);
}
}

The output is shown here:

a.x 10, b.x 20


a.x 20, b.x 30

As the output shows, after the assignment


a = b;

CS T73 PLATFORM TECHNOLOGY Page 54


The structure variables a and b are still separate and distinct. That is, a does not refer to or
relate to b in any way other than containing a copy of b’s value.
This would not be the case if a and b were class references. For example, here is the
class version of the preceding

Program:

// Copy a class.
using System;
// Define a structure.
class MyClass {
public int x;
}
// Now show a class object assignment.
class ClassAssignment {
public static void Main() {
MyClass a = new MyClass();
MyClass b = new MyClass();
a.x = 10;
b.x = 20;
Console.WriteLine("a.x {0}, b.x {1}", a.x, b.x);
a = b;
b.x = 30;PART I
Chapter 12: Interfaces, Structures, and Enumerations 329
Console.WriteLine("a.x {0}, b.x {1}", a.x, b.x);
}
}

The output from this version is shown here:


a.x 10, b.x 20
a.x 30, b.x 30
As you can see, after the assignment of b to a, both variables refer to same object—the one
originally referred to by b.

COLLECTIONS
Collection classes are specialized classes for data storage and retrieval.

These classes provide support for stacks, queues, lists, and hash tables. Most collection classes
implement the same interfaces.

CS T73 PLATFORM TECHNOLOGY Page 55


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. These classes create collections of
objects of the Object class, which is the base class for all data types in C#.

Various Collection Classes and Their Usage


The following are the various commonly used classes of the System.Collection namespace.
Click the following links to check their detail.

Class Description and Useage


It represents ordered collection of an object that can
be indexed individually.
It is basically an alternative to an array. However unlike
ArrayList array you can add and remove items from a list at a
specified position using an index and the array resizes
itself automatically. It also allows dynamic memory
allocation, add, search and sort items in the list.
It uses a key to access the elements in the collection.
A hash table is used when you need to access elements by
Hashtable using key, and you can identify a useful key value. Each
item in the hash table has a key/value pair. The key is
used to access the items in the collection.
It uses a key as well as an index to access the items in a
list.
A sorted list is a combination of an array and a hash table.
It contains a list of items that can be accessed using a key
SortedList or an index. If you access items using an index, it is an
ArrayList, and if you access items using a key , it is a
Hashtable. The collection of items is always sorted by the
key value.

It represents a last-in, first out collection of object.


It is used when you need a last-in, first-out access of
items. When you add an item in the list, it is
Stack
called pushing the item and when you remove it, it is
calledpopping the item.

It represents a first-in, first out collection of object.


It is used when you need a first-in, first-out access of
Queue items. When you add an item in the list, it is
called enqueue and when you remove an item, it is
calleddeque.

CS T73 PLATFORM TECHNOLOGY Page 56


It represents an array of the binary representation using
the values 1 and 0.
It is used when you need to store the bits but do not know
BitArray
the number of bits in advance. You can access items from
the BitArray collection by using an integer index, which
starts from zero.

REGULAR EXPRESSION

A regular expression is a pattern that could be matched against an input text. The .Net
framework provides a regular expression engine that allows such matching.

In theoretical computer science and formal language theory, a regular


expression (abbreviated regex or regexp) is a sequence ofcharacters that forms a search pattern,
mainly for use in pattern matching with strings, or string matching, i.e. "find and replace"-like
operations.

For example, the simple regexp ^[ \t]+|[ \t]+$ matches excess whitespace at the beginning or
end of a line.

The Regex Class


The Regex class is used for representing a regular expression.

The Regex class has the following commonly used methods:

S.N Methods & Description


public bool IsMatch( string input )
1 Indicates whether the regular expression specified in the Regex
constructor finds a match in a specified input string.
public bool IsMatch( string input, int startat )
Indicates whether the regular expression specified in the Regex
2
constructor finds a match in the specified input string, beginning
at the specified starting position in the string.
public static bool IsMatch( string input, string pattern )
3 Indicates whether the specified regular expression finds a match
in the specified input string.
public MatchCollection Matches( string input )
4 Searches the specified input string for all occurrences of a regular
expression.
5 public string Replace( string input, string replacement )
In a specified input string, replaces all strings that match a regular

CS T73 PLATFORM TECHNOLOGY Page 57


expression pattern with a specified replacement string.
public string[] Split( string input )
Splits an input string into an array of substrings at the positions
6
defined by a regular expression pattern specified in the Regex
constructor.
using System;
using System.Text.RegularExpressions;

namespace RegExApplication
{
class Program
{
private static void showMatch(string text, string expr)
{
Console.WriteLine("The Expression: " + expr);
MatchCollection mc = Regex.Matches(text, expr);
foreach (Match m in mc)
{
Console.WriteLine(m);
}
}
static void Main(string[] args)
{
string str = "A Thousand Splendid Suns";

Console.WriteLine("Matching words that start with 'S': ");


showMatch(str, @"\bS\S*");
Console.ReadKey();
}
}
}
Matching words that start with 'S':
The Expression: \bS\S*
Splendid
Suns

INHERITANCE

One of the most important concepts in object-oriented programming is that of


inheritance. Inheritance allows us to define a class in terms of another class, which makes it

CS T73 PLATFORM TECHNOLOGY Page 58


easier to create and maintain an application. This also provides an opportunity to reuse the code
functionality and fast implementation time.

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. This existing class is called the base class, and the new class is referred to as
the derived class.
The idea of inheritance implements the IS-A relationship. For example, mammal IS A animal,
dog IS-Amammal hence dog IS-A animal as well and so on.
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.

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

<acess-specifier> class <base_class>


{
...
}
class <derived_class> : <base_class>
{
...
}

Consider a base class Shape and its derived class Rectangle:

using System;
namespace InheritanceApplication
{
class Shape
{
public void setWidth(int w)
{
width = w;
}
public void setHeight(int h)
{
height = h;
}
protected int width;
protected int height;
}

// Derived class
class Rectangle: Shape

CS T73 PLATFORM TECHNOLOGY Page 59


{
public int getArea()
{
return (width * height);
}
}

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

Rect.setWidth(5);
Rect.setHeight(7);

// Print the area of the object.


Console.WriteLine("Total area: {0}", Rect.getArea());
Console.ReadKey();
}
}
}

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

Total area: 35

OPERATOR OVERLOADING

Overloaded operators are functions with special names the keyword operator followed by the
symbol for the operator being defined. Like any other function, an overloaded operator has a
return type and a parameter list.
For example, look at the following function:

public static Box operator+ (Box b, Box c)


{
Box box = new Box();
box.length = b.length + c.length;
box.breadth = b.breadth + c.breadth;
box.height = b.height + c.height;
return box;
}

CS T73 PLATFORM TECHNOLOGY Page 60


The above function implements the addition operator (+) for a user-defined class Box. It adds the
attributes of two Box objects and returns the resultant Box object.

Implementation of Operator Overloading


The following program shows the complete implementation:

using System;

namespace OperatorOvlApplication
{
class Box
{
private double length; // Length of a box
private double breadth; // Breadth of a box
private double height; // 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.
public static Box operator+ (Box b, Box c)
{
Box box = new Box();
box.length = b.length + c.length;
box.breadth = b.breadth + c.breadth;
box.height = b.height + c.height;
return box;
}

CS T73 PLATFORM TECHNOLOGY Page 61


class Tester
{
static void Main(string[] args)
{
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box(); // Declare Box2 of type Box
Box Box3 = new Box(); // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);

// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);

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

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

// Add two object as follows:


Box3 = Box1 + Box2;

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

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

Volume of Box1 : 210


Volume of Box2 : 1560
Volume of Box3 : 5400

CS T73 PLATFORM TECHNOLOGY Page 62


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.
These binary operators take one operand and can
+, -, *, /, %
be overloaded.
==, !=, <, >, <=, >= The comparison operators can be overloaded
The conditional logical operators cannot be
&&, ||
overloaded directly.
+=, -=, *=, /=, %= The assignment operators cannot be overloaded.
=, ., ?:, ->, new, is, sizeof, typeof These operators cannot be overloaded.

EVENTS

Events are basically a user action like key press, clicks, mouse movements, etc., or some
occurrence like system generated notifications. Applications need to respond to events when they
occur.

An event can have many handlers. With the event handler syntax, we create a notification
system.

To declare an event inside a class, first a delegate type


for the event must be declared.
Next:The event keyword is used to create an instance of
an event that can store methods in its invocation list.

using System;

public delegate void EventHandler();

class Program
{
public static event EventHandler _show;
static void Main()
{
// Add event handlers to Show event.
_show += new EventHandler(Dog);
CS T73 PLATFORM TECHNOLOGY Page 63
_show += new EventHandler(Cat);
_show += new EventHandler(Mouse);
_show += new EventHandler(Mouse);

// Invoke the event.


_show.Invoke();
}

static void Cat()


{
Console.WriteLine("Cat");
}

static void Dog()


{
Console.WriteLine("Dog");
}

static void Mouse()


{
Console.WriteLine("Mouse");
}
}

Output

Dog
Cat
Mouse
Mouse

Control flow begins in the Main entry point. The show event has four method instances added
to its invocation list with the plus "+=" operator. This has no relation to the arithmetic addition
operator.
Next:In the invocation list of the _show event, we add four events: Dog, Cat and two instances
of Mouse.
Finally:When the Invoke method is called, each of those method instances are called. The
strings are printed to the console.
Console.WriteLine

CS T73 PLATFORM TECHNOLOGY Page 64

You might also like