Unit 2
Unit 2
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
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.
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.
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.
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.
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:
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
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.
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.
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.
r = Math.Sqrt(area / 3.1416);
Console.WriteLine("Radius is " + r);
}}
The output from the program is shown here:
Radius is 1.78412203012729
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
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#
Variables are initialized (assigned a value) with an equal sign followed by a constant expression.
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;
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.
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();
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:
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:
The Bitwise operators supported by C# are listed in the following table. Assume variable A holds
60 and variable B holds 13 then:
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; /* 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);
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
EXAMPLE
using System;
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();
}
}
}
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
{
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
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
using System;
class IfSelect
{ string myInput;
int myInt;
myInput = Console.ReadLine();
myInt = Int32.Parse(myInput);
if (myInt > 0)
if (myInt < 0)
// Either/Or Decision
if (myInt != 0)
} else
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
string myInput;
begin:
myInput = Console.ReadLine();
myInt = Int32.Parse(myInput);
switch (myInt)
{ case 1:
break;
break;
case 3:
break;
default:
break; }
decide:
myInput = Console.ReadLine();
{ case "continue":
goto begin;
case "quit":
Console.WriteLine("Bye.");
break;
default:
goto decide;
} } }
• While loop.
• Do loop.
• For loop.
• Foreach loop.
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;
{ int myInt = 0;
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
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 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;
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++;
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;
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);
}
}
}
}
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
Method Overriding means having two or more methods with the same name, same
parameters but with different implementation.
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");
}
}
{
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();
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:
EXAMPLE
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InterfaceApplication
{
}
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
HANDLING EXCEPTION
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
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:
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:
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;
When the above code is compiled and executed, it produces the following result:
Value of Num: 35
Value of Num: 175
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.
Type name
Get
Set
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
OUTPUT
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 ([ ]).
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;
return (tmp);
}
set
{
if (index >= 0 && index <= size - 1)
{
namelist[index] = value;
}
}
}
OUTPUT
Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.
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.
General form:
In c# the square bracket comes after type. Single square bracket indicates one-
dimensional array.
Since arrays are implemented as objects, the creation of an array is a two-step process.
Step 2: Allocate memory for the array, assigning a reference to that memory to the array
variable by using new operator.
1) We can assign values to individual array elements, by using the index number, like:
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;
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
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:
DECLARATION
To declare a two-dimensional integer array of size 10, 20 (i.e.) 10 rows and 20 columns,
Note that the two-dimension arrays are separated from each other by a comma.
}
}
1 5 6 7 8
9 10 11 12
2
JAGGED 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.
X[1][0] X[1][1]
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;
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 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);
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.
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
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;
}
}
// 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);
}
}
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);
}
}
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.
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.
For example, the simple regexp ^[ \t]+|[ \t]+$ matches excess whitespace at the beginning or
end of a line.
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";
INHERITANCE
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.
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
class RectangleTester
{
static void Main(string[] args)
{
Rectangle Rect = new Rectangle();
Rect.setWidth(5);
Rect.setHeight(7);
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:
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
// 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);
// 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:
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.
using System;
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);
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