Вы находитесь на странице: 1из 42

ACKNOWLEDGEMENT

I take this opportunity to express my acknowledgement and deep sense of


gratitude to the following personalities for rendering valuable assistance
and guidance to me for the successful completion of summer training at
GURJOT INSTITUTE OF COMPUTER TECHNOLOGY (GICT)

I am very thankful to Mr. Manjeet Singh head of GICT for giving me a


chance to Undergo summer training.

I am very thankful to the faculty of the institute Mr. Manjeet Singh to guide
my training and His support and continuous help at all times during my
summer training.

I want to pay my special thanks to my parents without whose support and


care this training would not be a success.

1
PREFACE

C# (pronounced `c` sharp) is a new programming


language it has been developed by Microsoft corporation as part of there
.NET strategy to provide web based services. C # is a pure object oriented
language according to Microsoft chairman Bill Gates, the next
revolutionary step in software development will be to make the internet
intelligent.

C # is a simple but powerful language. It combines the


concept of C, C++ and elegance of java and productivity of visual basic.
Since Microsoft introduced C# as a de facto language of there .NET
platform. It supports all the key feature of .NET natively.

Since C# is the part of the part of .NET revolution, it


closely linked to .NET frame work. C# has object oriented feature such as
classes, inheritance, interfaces and polymorphism. It also introduced
several new features that are unique such as properties, indexes,
delegates, events and namespaces.

Large number of illustrations and example programs are provided to


reinforce learning. Whenever necessary, concepts are explained pictorially
to facilitates easy grasping and better understanding.

2
INTRODUCTION

C# (pronounced "C sharp") is a new language designed by Microsoft to


combine the power of C/C++ and the productivity of Visual Basic. Initial
language specifications also reveal obvious similarities to Java, including
syntax, strong web integration and automatic memory management. So, if
you have programmed in either C++ or Java, adding C# to your ken of
languages should be fairly straightforward.

The purpose of this article is to give a programmer, new to C#, an


introduction to the language. Even if you've never programmed in C/C++ or
Java before, this article is still basic enough for you. The only
assumptions made are that you have some kind of programming
background (some object-oriented experience would be helpful, but is not
necessary) and you have some kind of C# compiler (if you would like to run
the examples). At the time this article was written, Beta 1 of Microsoft’s.

W hy C# ?
As a technical leader (in MicrosoftTechnology) in Asia�s largest
consulting house Tata ConsultancyServices (TCS), I�ve been leading
various projects for various clientsover past two years. Publishing an
article was always in my mind (I�vewritten couple of articles on designing
COM components in Visual Basicand related problems), but never taken it
seriously. With variousarticles on .Net flashing in Microsoft site since
September 2000, I�vebeen closely following the development related to
.Net (Beta1 inJanuary and Beta2 in June�2001).�Currently Microsoft is
offering fourlanguages out of the box:
C#, VB.Net, Managed C++ and Jscript for application development on
.Netplatform and many more to come from various independent vendors.�
Sothe obvious question is which language is best suited for .Net?(Believe
me each time we meet for Technical Discussion, this has been afavorite
topic).

3
Managed C++
C++, even in its new managed form, definitelylags behind other languages
such as VB.NET and C# for their cleanersyntax and ease of use. So I
don�t expect any adition to the C++Developer community.�There's no
doubt, though, that experienced C++practitioners will continue to admire
and use its power, templates,multiple code inheritance and deterministic
finalisation.

C#
C# is the new language with the power of C++and the slickness of Visual
Basic.�It cleans up many of the syntacticpeculiarities of C++ without
diluting much of its flavour (therebyenabling C++ developers to transition
to it with little difficulty).�And its superiority over VB6 in facilitating
powerful OOimplementations is without question.C# with clean OO syntax
and large class library (in conjunction with.NET and the base class
libraries) could be the �most productivemainstream language� and it is
an ECMA-standard language that offersthe potential of being available
across many platforms.�For the serious developer wanting Microsoft's
most productive andmainstream .NET language, C# is the clear choice.

Features in C# 2.0

1. C# is a simple, modern, object oriented language derived from C++


and Java.

2. It aims to combine the high productivity of Visual Basic and the raw
power of C++.

3. It is a part of Microsoft Visual Studio7.0.

4. Visual studio supports Vb, VC++, C++, Vbscript, Jscript. All of these
languages provide access to the Microsoft .NET platform.

5. .NET includes a Common Execution engine and a rich class library.

6. Microsoft's JVM equiv. is Common language run time (CLR).

4
7. CLR accommodates more than one languages such as C#, VB.NET,
Jscript, ASP.NET, C++.

8. Source code --->Intermediate Language code (IL) ---> (JIT Compiler)


Native code.

9.The classes and data types are common to all of the .NET languages.

10. We may develop Console application, Windows application, and


Web application using C#.

11. In C# Microsoft has taken care of C++ problems such as Memory


management, pointers etc.

12.It supports garbage collection, automatic memory management and a


lot.

5
OVERVIEW OF C#
History of C#

C# was designed for developing components in a fully object-oriented


manner as part of the Microsoft .NET initiative. C# debuted in the year 2000
at the Professional Developers Conference (PDC) where Microsoft founder
Bill Gates was the keynote speaker. At the same time, Visual Studio .NET
was announced.

The primary architects of C# were Peter Golde, Eric Gunnerson, Anders


Hejlsberg, Peter Sollichy, and Scott Wiltamuth. Of these, the principal
designer of the the C# language was Anders Hejlsberg, a lead architect at
Microsoft. Previously, he was a framework designer with experience with
Visual J++ (Microsoft's old version of the Java language), Delphi, and
Turbo Pascal.

Both C# and the Common Language Infrastructure (CLI) have been


submitted to international standards organizations European Computer
Manufacturers Association (ECMA) and International Organization for
Standardization (ISO) / International Electrotechnical Commission (IEC).

Simple program of C#
Class sampleone
{
Public static void Main ()
{
System. Console. WriteLine(“C# is sharper than C++”);
}
}

6
LITERALS, VARIABLES AND
DATA TYPES

. Net C# Data Types


Data is physically stored inside cells of memory. This memory could be
physical memory (Hard disk) or logical memory (RAM). Any cell of memory
is represented with a unique address. This address is more than some
combination of numbers or symbols.

C# language provides for practically all the data types. These types can
be divided in three categories: value types, reference types and pointer
types.

There are some more basic concepts to be learnt before the discussion of
the data types. This is about variables and constants. A Variable is a
named cell of memory used for data storage. A Variable value can be
changed anytime. Every variable must have a type and this type must be
set before it is used. Qualifying a variable with a type is called as
declaration of variable. The type of a variable is the most important aspect
and it defines the behavior of variable. All variables can be divided into
seven main categories depending on the context of usage:

1. Static variables
2. Variable of instance
3. Array's elements
4. Parameters given by reference
5. Parameters given by value
6. Returned values
7. Local variables.

7
Common types in C#:
Object in C# language is universal; it means that all supported types are
derived from it. It contains only a couple of methods: Get Type() - returns a
type of object, To String() returns string equivalent of type that called.

Next type is class. It is declared in the same manner as structure type but it
has more advanced features.

Interface is an abstract type. It is used only for declaring type with some
abstract members. It means members without implementations. Please,
have a look at piece of code with a declaration for a simple interface:

interface IRect
{
int Width
{
get;
set;
}

int Height
{
get;
set;
}

int CalculateArea();
}

The members of interface can be methods, properties and indexers.

Next reference type to be dealt is delegate. The main goal of delegate


usage is encapsulation of methods. It most like at pointers to function in
C++.

String is common type that is used in almost all programming languages


of high level. An example of string declaration and initialization:

string s = "declaration and init";

8
Literals
A literal is a source code representation of a value.

literal:

boolean-literal

integer-literal
real-literal
character-literal
string-literal
null-literal

Variables
Variables represent storage locations. Every variable has a type that
determines the values to be stored in the variable. C# is a type-safe
language and the C# compiler guarantees that values stored in variables
are always of the appropriate type. The value of a variable can be changed
through assignment or through use of the ++ and - operators.

Variables are values that can change as much as needed during the
execution of a program. One reason you need variables in a program is to
hold the results of a calculation. Hence, variables are locations in memory
in which values can be stored.

Variable Declarations

In C# all variables must be declared before they are used. In the declaration
you must specify a data type and a name for the variable so that memory
can be set aside for the variable. An optional initial value can be included
with the declaration if you know what the value should be to start.

Syntax for variable declaration

[scope] [=initial value];

9
Description

The scope determines the accessibility of the variable (public, local,


private) and the default is private. The data type specifies what kind of data
the variable will hold. Optionally the variable can be initialised to a specific
value. All variables must be initialised (given a value) before they are used
in any calculation. If the variables are not initialised, the compilation of the
program will fail.

Value Type Variables

Value type variables are also known as stack variables because they are
stored on the stack. Value type variables can be directly declared and
referenced. As the variables go out of scope, they are removed from the
stack, ensuring the proper destruction of the variables. As the variables are
created on the stack, they are not initialised; that is the responsibility of the
program. The use of an uncapitalized variable will result in a compiler error.

Example Value variable

Int n; //uncapitalized int


Long l = 327 //initialised long
Float f = 3.13 F; //float initialised from single-precision literal

Reference Type Variables

Reference type variables are made up of two parts: the reference on the
stack and the object on the heap. The creation of the object and the
reference to the object is commonly known as the instantiation of the
object.

Example Reference variable

10
To declare a reference-type variable, the syntax used are:

string strMimico; city objToronto = null; object objGeneric;

Example Object variable

To create an object on the heap, we go through two steps, as follows:

1. Declare the variable reference.


2. Instantiate the object on the heap by calling the new operator.

City objMimico; //declare objMimico to be a reference to a an


// object of City type
objMimico = new City(); //call the constructor of the City class to return
// a reference that is stored in the objMimico reference

The two lines can be combined into one:

City objMimico = new City();

11
C# OPERATORS
There are 8 types of Operators in C#

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators

12
DECISION MAKING AND
BRANCHING

If Statements
if I lose ten pounds, I can get into my high-school bluejeans.

if(iCurrentWeight <= (iOriginalWeight – 10)){


highschool_jeans.Wear();
}

if the stock market crashes, Wall Street will panic.

if (blnStockMarketCrashed){
BenBernanki.FreakOut();
}

if the temperature drops to minus ten degrees overnight, our water pipes
will burst.

if (iTemperature <= -10){


pipes.FreezeAndBurst();
}

if we get at least $2500 in our tax return, we'll pay off the car; otherwise,
we'll apply it toward our credit card debt.

if (iReturnAmt >= 2500){


car.PayOff();
} else {
creditcard.PayDown();
}

As you can see, the basic structure of an if statement is:

if (condition){
// do this …
}

13
The switch statement
As you can see, if…else if…else can handle multiple choices. We could
have included several more else if above and the program would have
worked fine (assuming we didn't make a syntax error). But there is a better
way of handling multiple choices, and that is the switch statement, which
— like the if statement — is a way of controlling branching behavior in a
program. Personally, I prefer to use a switch statement anytime a simple
if…else won’t suffice. In other words, if we're not looking a simple either-or
case, but instead are dealing with multiple possibilities, it’s generally better
to use switch. The syntax of such a statement in C# looks like this:

switch(value){

case value1:
//code goes here
break;

case value2:
//code goes here
break;

.
.
.

case valueN:
//code goes here
break;

default:
//code goes here
break;

} //end switch statement

IF ELSE

if(blnHaveGun && blnHaveAmmo){

14
TargetPractice();

}else{

Console.WriteLine("No target practice today…");


}

DECISION MAKING AND


LOOPING

The While Statement:


The simplest of all looping structure in C is the while statement. The
general format of the while statement is:

15
while (test condition)
{
body of the loop
}

Here the given test condition is evaluated and if the condition is true then
the body of the loop is executed. After the execution of the body, the test
condition is once again evaluated and if it is true, the body is executed
once again. This process of repeated execution of the body continues
until the test condition finally becomes false and the control is transferred
out of the loop. On exit, the program continues with the statements
immediately after the body of the loop. The body of the loop may have one
or more statements. The braces are needed only if the body contained two
are more statements

Example program for generating ‘N’ Natural numbers using while loop:

# include < stdio.h > //include the stdio.h file


void main() // Start of your program
{
int n, i=0; //Declare and initialize the variables
printf(“Enter the upper limit number”); //Message to the user
scanf(“%d”, &n); //read and store the number
while(I < = n) // While statement with condition
{ // Body of the loop
printf(“\t%d”,I); // print the value of i
I++; increment I to the next natural number.
}
}

In the above program the looping concept is used to generate n natural


numbers. Here n and I are declared as integer variables and I is initialized
to value zero. A message is given to the user to enter the natural number
till where he wants to generate the numbers. The entered number is read
and stored by the scanf statement. The while loop then checks whether
the value of I is less than n i.e., the user entered number if it is true then

16
the control enters the loop body and prints the value of I using the printf
statement and increments the value of I to the next natural number this
process repeats till the value of I becomes equal to or greater than the
number given by the user.

The Do while statement:


The do while loop is also a kind of loop, which is similar to the while loop
in contrast to while loop, the do while loop tests at the bottom of the loop
after executing the body of the loop. Since the body of the loop is
executed first and then the loop condition is checked we can be assured
that the body of the loop is executed at least once.

The syntax of the do while loop is:

Do
{
statement;
}
while(expression);

Here the statement is executed, then expression is evaluated. If the


condition expression is true then the body is executed again and this
process continues till the conditional expression becomes false. When
the expression becomes false. When the expression becomes false the
loop terminates.

To realize the usefulness of the do while construct consider the following


problem. The user must be prompted to press Y or N. In reality the user
can press any key other than y or n. IN such case the message must be
shown again and the user should be allowed to enter one of the two keys,
clearly this is a loop construct. Also it has to be executed at least once.
The following program illustrates the solution.

/* Program to illustrate the do while loop*/


#include < stdio.h > //include stdio.h file to your program

17
void main() // start of your program
{
char inchar; // declaration of the character
do // start of the do loop
{
printf(“Input Y or N”); //message for the user
scanf(“%c”, &inchar); // read and store the character
}
while(inchar!=’y’ && inchar != ‘n’); //while loop ends
if(inchar==’y’) // checks whther entered character is y
printf(“you pressed u\n”); // message for the user
else
printf(“You pressed n\n”);
} //end of for loop

The Break Statement:


Sometimes while executing a loop it becomes desirable to skip a part of
the loop or quit the loop as soon as certain condition occurs, for example
consider searching a particular number in a set of 100 numbers as soon
as the search number is found it is desirable to terminate the loop. C
language permits a jump from one statement to another within a loop as
well as to jump out of the loop. The break statement allows us to
accomplish this task. A break statement provides an early exit from for,
while, do and switch constructs. A break causes the innermost enclosing
loop or switch to be exited immediately.

Example program to illustrate the use of break statement.

/* A program to find the average of the marks*/


#include < stdio.h > //include the stdio.h file to your program
void main() // Start of the program
{
int I, num=0; //declare the variables and initialize
float sum=0,average; //declare the variables and initialize
printf(“Input the marks, -1 to end\n”); // Message to the user
while(1) // While loop starts
{
scanf(“%d”,&I); // read and store the input number
if(I==-1) // check whether input number is -1

18
break; //if number –1 is input skip the loop
sum+=I; //else add the value of I to sum
num++ // increment num value by 1
}} end of the program

Continue statement:
During loop operations it may be necessary to skip a part of the body of
the loop under certain conditions. Like the break statement C supports
similar statement called continue statement. The continue statement
causes the loop to be continued with the next iteration after skipping any
statement in between. The continue with the next iteration the format of
the continue statement is simply:

Continue;

Consider the following program that finds the sum of five positive
integers. If a negative number is entered, the sum is not performed since
the remaining part of the loop is skipped using continue statement.

#include < stdio.h > //Include stdio.h file


void main() //start of the program
{
int I=1, num, sum=0; // declare and initialize the variables
for (I = 0; I < 5; I++) // for loop
{
printf(“Enter the integer”); //Message to the user
scanf(“%I”, &num); //read and store the number
if(num < 0) //check whether the number is less than zero
{
printf(“You have entered a negative number”); // message to the user
continue; // starts with the beginning of the loop
} // end of for loop
sum+=num; // add and store sum to num
}
printf(“The sum of positive numbers entered = %d”,sum); // print thte sum.

} // end of the program.

19
For Loop:
The for loop provides a more concise loop control structure. The general
form of the for loop is:

for (initialization; test condition; increment)


{
body of the loop
}

When the control enters for loop the variables used in for loop is
initialized with the starting value such as I=0,count=0. The value which
was initialized is then checked with the given test condition. The test
condition is a relational expression, such as I < 5 that checks whether the
given condition is satisfied or not if the given condition is satisfied the
control enters the body of the loop or else it will exit the loop. The body of
the loop is entered only if the test condition is satisfied and after the
completion of the execution of the loop the control is transferred back to
the increment part of the loop. The control variable is incremented using
an assignment statement such as I=I+1 or simply I++ and the new value of
the control variable is again tested to check whether it satisfies the loop
condition. If the value of the control variable satisfies then the body of the
loop is again executed. The process goes on till the control variable fails
to satisfy the condition.

Additional features of the for loop:

We can include multiple expressions in any of the fields of for loop


provided that we separate such expressions by commas. For example in
the for statement that begins

For( I = 0; j = 0; I < 10, j=j-10)

20
Sets up two index variables I and j the former initialized to zero and the
latter to 100 before the loop begins. Each time after the body of the loop is
executed, the value of I will be incremented by 1 while the value of j is
decremented by 10.

Just as the need may arise to include more than one expression in a
particular field of the for statement, so too may the need arise to omit on
or more fields from the for statement. This can be done simply by omitting
the desired filed, but by marking its place with a semicolon. The
init_expression field can simply be “left blank” in such a case as long as
the semicolon is still included:

For(;j!=100;++j)

METHODS IN C#
Introduction to C#
Methods :
Just in the beginning I like to remind all of you that Computer programs
exist to solve a problems and there are methods for solving those problems.

That's how I can explain the meaning of C# methods. All C# programs


constructed from a number of classes and those classes contain methods
that solve the problems for the program. So a methods is a kind of building

21
blocks that solve a small problem.

For example you have a problem in your program. You need a method to
convert a string to integer array for some reason. You can use the
following method :

private int[] ToIntArray(string s)


{
int o = s.Length;
int[] iArray = new int[o];
for(int x = 0; x < s.Length; x++)
{
iArray[x] = Convert.ToInt32(s.Substring(x,1));
}
return iArray;
}

So with this method we solve the problem we have here ( if we have a


string like "911" this method will convert it to integer array [9,1,1] ). We will
not talk about the code written inside the method now but we will focus on
introducing you to methods and later we will take a lot of examples. Just
note that we use the .NET Framework Class Library (FCL) methods (like
ToInt32(), Substring()) inside our methods to create a new methods. That's
make our job as a programmers much easier.

When you declare a variable in your method then it's a local variable to that
method and no other method can know anything about that variable.

Methods also very useful if you will use a block of code many times in your
program so instead of writing the same block of code many times in the
program we can put that code in a method and call it whenever we need it
to do the job.

How we write C# methods ?


After reading this section you will be able to write methods and understand
the concept of (Parameters, Return Value)

We have a line of code and we need to put it inside a method so we


understand how we can write C# methods.

Console.WriteLine(Math.Sqrt(9));

This line of code use the Sqrt method of the class Math to get the square
root of 9 . We need to create a method to write to the console screen the

22
square root just when we use it (when we call it, Invoke it). Let's take a look
at this method :

static void SqrtToConsole(double x)


{
Console.WriteLine(Math.Sqrt(x));
}

to understand this method we need to explain the concept of parameters.

Parameters and parameters value :


A lot of times the method you call will need some information from you to
complete its task. For example the ToIntArray() method in the article take
one parameter as a string :

private int[] ToIntArray(string s)<--------------- This is called a parameter

So this place where we will put the string into called a parameter. We just
tell the method "You have one place (a parameter) where can the user put a
value here (a parameter value) and you need this value to finish your task".
So when you create the method you specify the parameters that the
method will use and when you call it you will specify the parameters value
for the parameters. parameters value are the values that you specify for
your parameters when you call the function. Every parameters in your
method has a data type exactly like variables and you must specify it when
you create the method. When you call the method you must specify the
parameters value of the same data type or to a type that can be converted
to that type. The parameters of any method not accessible outside the
method because it's considered as local variables for that method.

Consider the following example :

static void SqrtToConsole(double x)<--------------- This is called a parameter


{
Console.WriteLine(Math.Sqrt(x));
}

We just created a method called SqrtToConsole that take only one


parameter. Now we need to call the method ( I mean we need to use the
method).

SqrtToConsole(9)<--------------- This is called a parameter value

23
We called the method SqrtToConsole with 9 as a parameter value for the
parameter x.

I think after you understand the concept of Parameters we can explain the
code written in the method SqrtToConsole.

static void SqrtToConsole(double x)


{
Console.WriteLine(Math.Sqrt(x));
}

We just created a method called SqrtToConsole with one parameter called


x of double data type. We use 2 FCL functions here (WriteLine(),Sqrt()) to
complete the task.

The Console.WriteLine() method take one parameter value to write it to the


console. Note that the parameter value of this parameter can be an
expression . There are 18 overloaded version of Console.WriteLine()
method and you can check them in Visual Studio.NET Documentation.
Some of them take a parameter value as a string, int, double, object and
other data types.

The Math.Sqrt() method take also one parameter value to get its job done.
Here we just create our method and inside it we call the
Console.WriteLine() with a parameter value as the result of the following
method call Math.Sqrt(x).

Note : Don't forget that x is the parameter of the SqrtToConsole() method


and we just use it in the Math.Sqrt(x) method so that we tell the compiler to
take the parameter value of SqrtToConsole() method and give it to the
Math.Sqrt()so the result will write to the console application.

Return Value :
Let's look at the Math.Sqrt() again please. This method takes a parameter of
double data type and Returns the square root of that parameter so this is
the return value that we are talking about here in C# methods.

Consider the following method :

private int AddIntegers(int x, int y)


{
return x + y ;

24
}

Here the AddIntegers() method takes 2 integer numbers and return the
result as integer too.

The return value must have a type so here in our method the return value is
of type int and we must write int keyword before the method name to
specify the return type. Also we use the return keyword as the end of our
method to exit the method and return the value to the method which called
the AddIntegers() ( I will explain how we can call method from other method
later ) . So when you use the return keyword you tell the compiler to end
the method and return a value of the specified type to the calling code. If
your method does not return a value then you must use the void keyword
in the same place as you do with the return value type (before the method
name).

You must understand something called Method Signature or Method


Definition. The group of method name, parameter list, return value type
specify the method signature or method definition. For example the method
AddIntegers() signature is :

1- The return data type (int)

2- The method name ( AddIntegers )

3- The parameter list ( (int x, int y) )

How we call a method ?

As you might know that the Main method is the entry point of any C#
program so it's the first method that the compiler will invoke. So any
method we created or any method we used it from FCL will be called from
the Main method. Consider the following example :

We have 2 methods as following :

private void Parent()


{
// We don't need any code here
}
private void Son(int x)
{
// We don't need any code here
}

25
We need to call this methods from our Main method. All what we need to do
like that

static void Main(string[] args)


{
Parent();
Son(23);
}

We called the 2 methods simply by typing the name of the method with 2
empty parenthesis if the method's parameter list is empty or the with
parameters values inside the parenthesis if the method's parameter list
contains parameters.

STRUCTURES AND
ENUMURATIONS
Structures
Structures are basically value types. They are defined by using the struct
keyword. You can access the variables inside a structure by creating an
object of the structure. The only difference is that you don't have to use the
syntax for creating an object from a class for structures. Listing 1 explains
this concept clearly.

26
Listing 1

using System;
enum Employees:byte
{
ok = 50,cancel = 100
}

struct Emp
{
public Employees EM;
public string id;
}

class Emptest
{
public static void Main()
{
Emp E;
E.EM = Employees.cancel;
E.id = "002";
Console.WriteLine(E.EM);
Console.WriteLine(E.id);
}
}

Enumerations

27
Enumerations are a set of names for the corresponding numerical values.
Normally, we use them to apply the code

Listing 2

case 1:
Console.WriteLine("OK");
break;

case 2:
Console.WriteLine("CANCEL");
break;

Instead of 1 and 2 as in Listing 2, you can use meaningful constants like


OK and CANCEL. This can be achieved through Enumerations.

Enumerations are defined using the enum keyword

Listing 3

enum Employees
{
OK; //
CANCEL;
}

The Employees enumeration defines two constants, OK and CANCEL. Each


constant has its own numerical value. By default, the numbering system
starts at 0. However, you can change the order

Listing 4

28
enum Employees
{
OK = 50; //
CANCEL = 100;
}

Also, the data type for each constant in an enumeration is an integer by


default, but you can change the type to byte, long, and so forth

Listing 5

enum Employees : byte


{
OK = 50;
CANCEL = 100;
}

Listing 6 below illustrates how to apply the Employees enumeration in a C#


program.

Listing 6

using System;
enum Employees
{
Instructors,
Assistants,
Counsellors
}

class Employeesenum
{
public static void Display(Employees e)

29
{

switch(e)
{
case Employees.Instructors:
Console.WriteLine("You are an Instructor");
break;

case Employees.Assistants:
Console.WriteLine("You are one of the Assistants");
break;

case Employees.Counsellors:
Console.WriteLine("You are a counsellor");
break;

default:break;
}

public static void Main(String[] args)


{
Employees emp;
emp = Employees.Counsellors;
Display(emp);
}

30
CLASSES AND OBJECTS
Introduction to Objects and Classes in C# -
Prog rammer’s Classes and Objects

A C# Class is considered to be the primary building block of the language.


What I mean by the primary building block is that every time you work with
C# you will create classes to form a program. We use classes as a template
to put the properties and functionalities or behaviors in one building block
for a group of objects and after that we use the template to create the
objects we need.

For example, we need to have persons objects in our program so the first

31
thing to do here is to create a class called Person that contains all the
functionalities or behaviors and properties of any person and after that we
will use that class (or template) to create as many objects as we need.
Creating an object of a specific class type is called "an instance of the
class". Don't worry if you didn't grasp it 100% and don't worry if you don't
know what the class and object's properties and functionalities or
behaviors are because we are still in the beginning. Until now I haven’t
provided any code examples. So let's take a brief of what is a class and
what is an object:

The class: A building block that contains the properties and functionalities
that describe some group of objects. We can create a class Person that
contains:

1. The properties of any normal person on the earth like: hair color,
age, height, weight, eye color.
2. The functionalities or behaviors of any normal person on the earth
like: drink water, eat, go to the work.

Later we will see how we can implement the functionalities or behaviors


and properties.

There are 2 kinds of classes: The built-it classes that come with the .NET
Framework , called Framework Class Library, and the programmer
defined-classes which we create ourselves.

The class contains data (in the form of variables and properties) and
behaviors (in the form of methods to process these data). We will
understand this concept later on in the article.

When we declare a variable in a class we call it member variables or


instance variables. The name instance come from the fact that when we
create an object we instantiate a class to create that object. So instance of
a class means an object of that class and instance variable means variable
that exists in that class.

The object: It's an object of some classification (or class, or type) and when
you create the object you can specify the properties of that object. What I
mean here is: I, as an object, can have different properties (hair color, age,
height, weight) than you as another object. For example, I have brown eyes
and you have green eyes. When I create 2 objects I will specify a brown
color for my object's eye color property and I will specify a green color for
your object's eye color property.

32
OPERATOR OVERLOADING
Operator Overloading in C#
Description

The Source code below shows how to use OperatorOverloading in C#.


Operator Overloading is pretty useful concept derived from C++ by C#.For
eg.

We can have class Matrix which hold 2D array of elements.C# add doest
not Allows us to do Addition, Subtraction of matrices using the +,- operator
rather We use to write Methods AddMatrix(),SubMatrix() with the use of
Operator.

33
Overloading we make the user to code it:

M3=M1+M2 where M1 and M2 are matrix objects.

Some Tips while using Operator overloading:

1. While OverLoading a Operator always give public static access


specifiers.

2. Operator Overloading should return a CLS type and not void.

3. Atleast one operand to the operator must be of type UDC [User


Defined Class] because we cannot overload a operator with two int
operands and perform subtraction for + operator which C# does not
allow.

4. Relational Operators are overloaded in Pairs only.ie if == is


overloaded then So !=.

5. Same Operator can be overloaded with different function signature


for eg.
public static Matrix operator +(Matrix m1,int[,] m2)
{
}

we can also one more method like this:


public static Matrix operator + (Matrix m1,Matrix m2)
{
}

Please find to the code which uses overloading of almost all


operators.

Source Code:

// Source Code starts


using System;
class Square
{
private double Side;
//public Constructor if int is passed convert to double and assign to Side
public Square(int s)
{
Console.WriteLine(".ctor with int argument");
Side=(double)s;
}

34
//OverLoaded constructor with double argument
public Square(double s)
{
Console.WriteLine(".ctor with double argument");
Side=s;
}
//override ToString() method of object class.
public override string ToString()
{
Console.WriteLine("Override object class's string");
return this.Side.ToString();
}
//Overloading + operator to add 2 square objects and return new square
object
public static Square operator + (Square x,Square y)
{
Console.WriteLine("Overloading + with Square,Square");
return new Square(x.Side+y.Side);
}
//Overloading + operator to add square objects with double side and return
new square object
public static Square operator + (Square x,double y)
{
Console.WriteLine("Overloading + with Square,double");
return new Square(x.Side+y);
}
//Overloading + operator to add square objects with int side and return new
square object
//This is not necessary since C# automatically calls +(Square,double)
public static Square operator + (Square x,int y)
{
Console.WriteLine("Overloading + with Square,int");
return x +(double)y;
}
public static implicit operator Square(double s)
{
Console.WriteLine("Overloading = for Square s5=1.5 assignment");
return new Square(s);
}
public static implicit operator Square(int s)
{
Console.WriteLine("Overloading = for Square s5=10 assignment");
return new Square((double)s);
}
//OverLoading == operator
public static bool operator ==(Square x,Square y)

35
{
Console.WriteLine("Overloading == with Square,Square");
return x.Side==y.Side;
}
//OverLoading != operator
public static bool operator !=(Square x,Square y)
{
Console.WriteLine("Overloading != with Square,Square");
return !(x==y); //This will call to operator == simple way to implement !=
}
//Always override GetHashCode(),Equals when overloading ==
public override bool Equals(object o)
{
return this==(Square)o;
}
public override int GetHashCode()
{
return (int)Side;
}
//OverLoading > operator
public static bool operator >(Square x,Square y)
{
Console.WriteLine("Overloading > with Square,Square");
return x.Side>y.Side;
}
//OverLoading < operator
public static bool operator <(Square x,Square y)
{
Console.WriteLine("Overloading < with Square,Square");
return x.Side<y.Side;
}
//OverLoading <= operator
public static bool operator <=(Square x,Square y)
{
Console.WriteLine("Overloading <= with Square,Square");
return (x<y) || (x==y); //Calls to operator == and <
}
//OverLoading >= operator
public static bool operator >=(Square x,Square y)
{
Console.WriteLine("Overloading >= with Square,Square");
return (x>y) || (x==y); //Calls to operator == and >
}
//Readonly Property
public double Area
{

36
get
{
return 2*Side;
}
}
public static void Main()
{
Square s1=new Square(10);
Square s2=new Square(20);
Square s3=s1+s2; // This will call operator + (Square,Square)
Console.WriteLine(s3);
Console.WriteLine(s3+15); // This will call operator + (Square,int) and then
ToString()
Console.WriteLine(s3+1.5);// This will call operator + (Square,double) and
then ToString()
s3=10; // This will call operator Square(int)
Console.WriteLine(s3);
Square s4=10;
Console.WriteLine(s1==s4); //Calls == operator
Console.WriteLine(s1!=s4); //Calls != operator
Console.WriteLine(s1>s2); //Calls > operator
Console.WriteLine(s1<=s4); //Calls <= operator
}
}
// Source Code End

MANAGING ERRORS AND


EXCEPTIONS
Exception Handling in C#
Exception handling is an in built mechanism in .NET framework to detect
and handle run time errors. The .NET framework contains lots of standard
exceptions. The exceptions are anomalies that occur during the execution
of a program. They can be because of user, logic or system errors. If a user
(programmer) do not provide a mechanism to handle these anomalies,
the .NET run time environment provide a default mechanism, which
terminates the program execution.

C# provides three keywords try, catch and finally to do exception handling.


The try encloses the statements that might throw an exception whereas
catch handles an exception if one exists. The finally can be used for doing

37
any clean up process.

The general form try-catch-finally in C# is shown below

try
{
// Statement which can cause an exception.
}
catch(Type x)
{
// Statements for handling the exception
}
finally
{
//Any cleanup code
}

If any exception occurs inside the try block, the control transfers to the
appropriate catch block and later to the finally block.

But in C#, both catch and finally blocks are optional. The try block can exist
either with one or more catch blocks or a finally block or with both catch
and finally blocks.

If there is no exception occurred inside the try block, the control directly
transfers to finally block. We can say that the statements inside the finally
block is executed always. Note that it is an error to transfer control out of a
finally block by using break, continue, return or goto.

In C#, exceptions are nothing but objects of the type Exception. The
Exception is the ultimate base class for any exceptions in C#. The C# itself
provides couple of standard exceptions. Or even the user can create their
own exception classes, provided that this should inherit from either
Exception class or one of the standard derived classes of Exception class
like DivideByZeroExcpetion ot ArgumentException etc.

Standard Exceptions
There are two types of exceptions: exceptions generated by an executing
program and exceptions generated by the common language runtime.
System.Exception is the base class for all exceptions in C#. Several
exception classes inherit from this class including ApplicationException
and SystemException. These two classes form the basis for most other
runtime exceptions. Other exceptions that derive directly from
System.Exception include IOException, WebException etc.

38
The common language runtime throws SystemException. The
ApplicationException is thrown by a user program rather than the runtime.
The SystemException includes the ExecutionEngineException,
StaclOverFlowException etc. It is not recommended that we catch
SystemExceptions nor is it good programming practice to throw
SystemExceptions in our applications.

• System.OutOfMemoryException
• System.NullReferenceException
• Syste.InvalidCastException
• Syste.ArrayTypeMismatchException
• System.IndexOutOfRangeException
• System.ArithmeticException
• System.DevideByZeroException
• System.OverFlowException

User-defined Exceptions
In C#, it is possible to create our own exception class. But Exception must
be the ultimate base class for all exceptions in C#. So the user-defined
exception classes must inherit from either Exception class or one of its
standard derived classes.

//C#: Exception Handling: User defined exceptions


using System;
class MyException : Exception
{
public MyException(string str)
{
Console.WriteLine("User defined exception");
}
}
class MyClient
{
public static void Main()
{
try
{
throw new MyException("RAJESH");
}
catch(Exception e)
{
Console.WriteLine("Exception caught here" + e.ToString());
}
Console.WriteLine("LAST STATEMENT");

39
}
}

DELEGATES AND EVENTS


Delegates
A delegate in C# is similar to a function pointer in C or C++. Using a
delegate allows the programmer to encapsulate a reference to a method
inside a delegate object. The delegate object can then be passed to code
which can call the referenced method, without having to know at compile
time which method will be invoked. Unlike function pointers in C or C++,
delegates are object-oriented, type-safe, and secure.

A delegate declaration defines a type that encapsulates a method with a


particular set of arguments and return type. For static methods, a delegate
object encapsulates the method to be called. For instance methods, a
delegate object encapsulates both an instance and a method on the
instance. If you have a delegate object and an appropriate set of
arguments, you can invoke the delegate with the arguments.

40
An interesting and useful property of a delegate is that it does not know or
care about the class of the object that it references. Any object will do; all
that matters is that the method's argument types and return type match the
delegate's. This makes delegates perfectly suited for "anonymous"
invocation.

Events
Events enable a class or object to notify other classes or objects when
something of interest occurs. The class that sends (or raises) the event is
called the publisher and the classes that receive (or handle) the event are
called subscribers.

In a typical C# Windows Forms or Web application, you subscribe to events


raised by controls such as buttons and list boxes. You can use the Visual
C# integrated development environment (IDE) to browse the events that a
control publishes and select the ones that you want to handle. The IDE
automatically adds an empty event handler method and the code to
subscribe to the event.

Events Overview

Events have the following properties:

• The publisher determines when an event is raised; the subscribers


determine what action is taken in response to the event.
• An event can have multiple subscribers. A subscriber can handle
multiple events from multiple publishers.
• Events that have no subscribers are never raised.
• Events are typically used to signal user actions such as button clicks
or menu selections in graphical user interfaces.
• When an event has multiple subscribers, the event handlers are
invoked synchronously when an event is raised. To invoke events
asynchronously, see Calling Synchronous Methods Asynchronously.
• Events can be used to synchronize threads.

41
• In the .NET Framework class library, events are based on the
EventHandler delegate and the EventArgs base class.

42