Anda di halaman 1dari 62

DOT Net Technologies

Unit 2

Unit 2
Structure: 2.1 Introduction Objectives 2.2 2.3 2.4 2.5 2.6 2.7 2.8

Introducing C# Programming

Creating your first C# Program Introducing Data Types Control Statements Understanding Properties & Indexes Delegates and Events Exception Handling Summary Self Assessment Questions

2.9 2.10

Terminal Questions Answers to Self Assessment Questions

2.1 Introduction
The C# language (pronounced as C Sharp or see Sharp) is an Object Oriented Programming Language developed by Microsoft to become a key part of their .Net software development platform. The C# language is based on the C++ Language, but it is mostly developed on the lines of Microsofts Visual Basic. The .NET Framework defines a "Common Language Specification" ( CLS), a sort of lingua franca that ensures seamless interoperability between CLScompliant languages and class libraries. For C# developers, this means that even though C# is a new language, it has complete access to the same rich class libraries that are used by seasoned tools such as Visual Basic .NET and Visual C++ .NET. C# itself does not include a class library.

Sikkim Manipal University

Page No. 22

DOT Net Technologies

Unit 2

The principal designer of the C# language was Anders Hajlsberg. C# was designed to take advantage of the Common Language Runtime (CLR) that .Net program rely on. All applications written in C# require CLR to run. The Cornerstone components of .Net Platform: There are four major cornerstone components of .Net platform as follows: 1. .Net Building Block services such as Passport 2. .Net Compact Framework that runs on devices such as mobile phones 3. .Net through XML integration 4. .Net infrastructure such as the .Net framework CLR and .Net framework class libraries and application developments such as Microsoft Visual Studio.Net All the .Net programming languages have the .Net framework class libraries integrated into them. The .Net class libraries also support functions such as file I/O, database operations, XML and SOAP. Sample Program: This is just a basic program that illustrates how a C# program looks like.
public class Class1 { public static void Main() { System.Console.WriteLine( Welcome to C#); } } Figure 2.1: A Sample C# Program

The output of this program would be Welcome to C# on the console. Objectives This unit is an introduction to Microsofts C# programming Language developed exclusively to allow interoperability features in .Net environment.
Sikkim Manipal University Page No. 23

DOT Net Technologies

Unit 2

At the end of this unit the student would be able to: Describe the importance of C# in Web Application development and highlight its features Describe the step-by-step procedure to edit, compile, and run Command based C# programs. Discuss the data types available in C#. Write programs using control statements of C#. Discuss about Properties, Indexes, Delegates and Events. Describe the Excpetion handling mechanisms used in C#.

2.2 Creating your first C# Program


It would be very easy to create, compile and run a C# program by following the steps illustrated in the following topics Compiling and Executing The minimum requirements for getting started with C# programming are: 1. A text editor (like Windows Notepad) 2. The Microsoft .NET Framework The text editor allows you to type in the C# code that will be compiled.

Figure 2.2: The sample program typed in Notepad

Sikkim Manipal University

Page No. 24

DOT Net Technologies

Unit 2

The Microsoft .Net Framework In addition to the text editor, you should have the Microsoft .Net Framework installed on your PC or Laptop.

Figure 2.3: The sample program saved as filename.cs from notepad

Figure 2.4: Compiling and executing the sample C# program

You can download the latest version of the .NET Framework from the following URL: http://msdn.microsoft.com/netframework/.

Sikkim Manipal University

Page No. 25

DOT Net Technologies

Unit 2

Steps for writing and compiling the C# code: Step 1: Type the C# code in the notepad as shown below:

Figure 2.5: Step 1: Keying a program in an editor

Step 2: Save the file into the folder containing the folder corresponding to C#. In my machine it is: C:\Program Files\Microsoft Visual Studio\SDK\V2.0> Save the notepad file as shown below:

Figure 2.6: Step 2 Saving the program into the directory or folder

Sikkim Manipal University

Page No. 26

DOT Net Technologies

Unit 2

Step 3: Open the command prompt (Start -> Run and type cmd and click OK) and navigate to the folder where you have saved the file. Alternatively you can start the command window from Windows Start Menu as shown below:

Figure 2.7: Step - 3: Opening the command prompt window

Step 4: Now we are ready to compile the program from the C# command line. The compiler used here is called csc.exe and is in the folder v2.0 of SDK. The syntax for compiling the sample C# program is:

csc.exe <filename>.cs
The name of our C# program is hello.cs. The syntax for compilation of the above program file is: csc.exe hello.cs

Sikkim Manipal University

Page No. 27

DOT Net Technologies

Unit 2

The following diagram illustrates the steps of the compilation of the sample program.

Figure 2.8: Step - 4: Compiling the program at the Command Prompt

Step 5: The source code is now compiled into an executable format. The name of the executable file thus generated is hello.exe, which is having the same name as the source code file name, except that the .cs extension is replaced by the .exe extension. To run the executable file, the following command should be typed at the command prompt: hello.exe The executable file gets executed by the environment and the string message Welcome to C# would be displayed on the console window.

Figure 2.9: Output of the Sample Program Sikkim Manipal University Page No. 28

DOT Net Technologies

Unit 2

A C# program can consist of more than one source file. The source files are turned into programs using a compiler. csc: It is the C# compiler that ships with the .Net Framework. The source code hello.cs is the C# source file passed to the compiler as an argument for compilation.

Figure 2.10: Sample Program Modified

using System: The using directive refers to a namespace called System, provided by the Common Language Infrastructure (CLI ), a synonym for the .Net Framework. The System namespace contains the Console class. The using Directive: By using this directive, we can make use of the unqualified types that are members of the namespace, i.e. it allows us to use only the command Console.WriteLine() instead of the entire command System.Console.WriteLine(). Defining a Class C# is an object-oriented programming language and uses classes and structs to implement types such as Windows Forms, user interface controls, and data structures. A typical C# application consists of classes defined by the programmer, combined with classes from the .NET Framework. Classes enable you to develop applications using object-oriented

programming (OOP) techniques. Classes are templates that define objects.


Sikkim Manipal University Page No. 29

DOT Net Technologies

Unit 2

When you create a new form in a C# project, you are actually creating a class that defines a form; forms instantiated at runtime are derived from the class. Using objects derived from predefined classes, such as a C# Form class, is just the start of enjoying the benefits of object-oriented programming to truly realize the benefits of OOP, you must create your own classes. All generic class declarations will have one or more type parameters. C# provides many powerful ways of defining classes, such as providing different access levels, inheriting features from other classes, and enabling the programmer to specify what occurs when types are instantiated or destroyed. Classes can also be defined as generic by using type parameters that enable client code to customize the class in a type-safe and efficient manner.A single generic class, for example System.Collections.

Generic.List(T) in the .NET Framework can be used by client code to store integers, strings, or any other type of object. A class is the most powerful data type in C#. Like structures, a class defines the data and behavior of the data type. Programmers can then create objects that are instances of this class. Unlike structures, classes support inheritance, which is a fundamental part of object-oriented programming. Declaring Classes Classes are defined by using the class keyword, as shown in the following example:

Figure 2.11: Declaration of classes in C# Sikkim Manipal University Page No. 30

DOT Net Technologies

Unit 2

The class keyword is preceded by the access level. Because public is used in this case, anyone can create objects from this class. The name of the class follows the class keyword. The remainder of the definition is the class body, where the behavior and data are defined. Fields, properties, methods, and events on a class are collectively referred to as class members. Creating Objects Although they are sometimes used interchangeably, a class and an object are different things. A class defines a type of object, but it is not an object itself. An object is a concrete entity based on a class, and is sometimes referred to as an instance of a class. Objects can be created by using the new keyword followed by the name of the class that the object will be based on, like this:

Figure 2.12: Creating Objects from a Class

When an instance of a class is created, a reference to the object is passed back to the programmer. In the previous example, object1 is a reference to an object that is based on Customer. This reference refers to the new object but does not contain the object data itself. In fact, you can create an object reference without creating an object at all.

Figure 2.13: Creation of an Object Reference

We do not recommend creating object references such as this one that does not refer to an object because trying to access an object through such a reference will fail at run time. However, such a reference can be made to refer to an object, either by creating a new object, or by assigning it to an existing object, such as this:
Sikkim Manipal University Page No. 31

DOT Net Technologies

Unit 2

Figure 2.14: Creation of Object References

This code creates two object references that both refer to the same object. Therefore, any changes to the object made through object3 will be reflected in subsequent uses of object4. Because objects that are based on classes are referred to by reference, classes are known as reference types. Declaring the Main() method: The Main() method is a member of the class Hello1 (as in Program 2.10). It is the point at which the application execution begins, i.e. it is the entry point for the application. There can only be one entry point in a C# program. The Main method can be declared with or without parameters. Parameters can be read as zero-indexed command line arguments. A Static Modifier is used so that the method it is assigned to becomes a method of the class rather than an instance of the class. Using the using keyword: The using keyword has two major uses: 1. As a Directive: When it is used to create an alias for a namespace or to import types defined in other namespaces. The using directive has two uses: To allow the use of types in a namespace so that you do not have to qualify the use of a type in that namespace:

Figure Usage of types in the namespace

Sikkim Manipal University

Page No. 32

DOT Net Technologies

Unit 2

To create an alias for a namespace or a type.

Figure Creation of Aliases for namespaces or types

2. As a Statement: When it defines a scope at the end of which an object will be disposed. It helps the users or the programmers to ensure that IDisposable objects such as files and fonts are handled correctly. Adding Comments The following console program is the C# version of the traditional "Hello World!" program, which displays the string Hello World!.

Figure 2.17: A Sample Hello World Program with Comments

The line //A Hello World program in C# is a single line comment, which would be ignored by the compiler during compilation or execution. There are two types of comment statements within C# Language similar to that of Java or C++ language syntax elements. 1. Single Line Comments: A one line comment can be given within a program using // 2. Multi Line Comments: A comment can be extended beyond a single line by enclosing all the statements within /* and */.

Sikkim Manipal University

Page No. 33

DOT Net Technologies

Unit 2

2.3 Introducing Data Types


A Type is how a programming language classifies different values and expressions. Since the computer stores all the data internally in the form of zeros and ones, the data needs to have a context or meaning. In order to preserve this meaning, Types are used in a programming language. Since C# is a strongly typed language; every variable and object used as part of the programs must have a declared type. In any programming language, it's critical that the compiler, the part of the Visual Studio framework that interprets the code you write into a language the computer can understand, fully understands the type of data you're manipulating in code. For example, if you ask the compiler to add the following values, it would get confused: 659 / "Dog" When the compiler gets confused, it either refuses to compile the code (which is the preferred situation because you can address the problem before your users run the application), or it will halt execution and display an exception (error) when it reaches the confusing line of code. Obviously, you can't subtract 659 by the word "Dog"; these two values are different types of data. In C#, these two values are said to have two different data types. In C#, constants, variables, and arrays must always be defined to hold a specific type of information. Determining the Data Type Data Typing: The act of defining a constant, a variable, or an array's data type can be confusing. To C#, a number is not a number. A number that contains a decimal value is different from a number that does not. C# can perform arithmetic on numbers of different data types, but you can't store data of one type in a variable with an incompatible type. Because of this limitation, you must give careful consideration to the type of data you plan to
Sikkim Manipal University Page No. 34

DOT Net Technologies

Unit 2

store in a constant, a variable, or an array at the time you define it. C# supports two categories of data types: value types and reference types. The main difference between these two types is how their values are stored in memory. As you continue to create more complex applications, this difference may have an impact on your programming. Overview of C# Data Types A Data Type can be described as being either: A built-in numeric type, such as an int or char, or A user-defined type, such as a class or interface. An anonymous type, which consists of a set of public properties encapsulated in a nameless reference type. Types can also be defined as being either: Value Types (C# Reference), which store values. These include the primitive numeric types, enums and structs, and also nullable versions of these types. Reference Types (C# Reference), which store references to the actual data. These include classes, interfaces, arrays and delegates. Value Types The value types consist of two main categories: Structs Enumerations Structs fall into these categories: Numeric types Integral types Floating-point types Decimal

Bool User defined structs


Sikkim Manipal University Page No. 35

DOT Net Technologies

Unit 2

Main Features of Value Types: Variables that are based on value types directly contain values. Assigning one value type variable to another copies the contained value. This differs from the assignment of reference type variables, which copies a reference to the object but not the object itself. All value types are derived implicitly from the System.ValueType. Unlike with reference types, you can derive a new type from a value type. However, like reference types, structs can implement interfaces. Unlike reference types, a value type cannot contain the null value. However, the nullable types feature does allow for values types to be assigned to null. Each value type has an implicit default constructor that initializes the default value of that type. Each of the variables will have their own copy of the data and an operation on one copy does not affect the others. All of the simple types those integral to the C# language -- are aliases of the .NET Framework System types. For example, int is an alias of System.Int32. Constant expressions, whose operands are all simple type constants, are evaluated at compilation time. Simple types can be initialized by using literals. For example, 'A' is a literal of the type char and 2001 is a literal of the type int. Initializing Value Types Local variables in C# must be initialized before they are used. For example, you might declare a local variable without initialization as in the following example: int i1;

Sikkim Manipal University

Page No. 36

DOT Net Technologies

Unit 2

You cannot use i1 before initializing. To initialize we can use the following statement: i1 = new int(); // Invokes the default constructor for the int data type. The above initialization statement is equivalent to: i1 = 0; Alternatively, you can have the above two statements combined into a single statement:

OR

Either of the above statements are correct. Using the new operator calls the default constructor of the specific type and assigns the default value to the variable. In the preceding example, the default constructor assigned the value 0 to i1. We can use the new operator to invoke the default constructor with user defined data types. For example, the following statement invokes the default constructor of the Point struct:

After this call, the struct is considered to be definitely assigned; i.e. all its members are initialized to their default values.

Sikkim Manipal University

Page No. 37

DOT Net Technologies

Unit 2

Primitive Data Types The following reference tables summarize the C# types: Built-in Integral Floating - point 1. Built in Data Types
C# Type .NET Framework Type System.Boolean Meaning

bool

An alias of System.Boolean and is used to declare variables to store the Boolean values, true and false. Note: If you require a Boolean variable that can also have a value of null, use bool. An unsigned 8-bit integer A signed 8-bit integer Used to declare a Unicode character. Constants of the char type can be written as character literals, hexadecimal escape sequence, or Unicode representation. You can also cast the integral character codes. Indicates a 128-bit data type. Compared to floatingpoint types, the decimal type has more precision and a smaller range, which makes it appropriate for financial and monetary calculations. The double keyword signifies a simple type that stores 64-bit floating-point values. Note: To treat an integer number as double, use the suffix d or D A simple type that stores 32-bit floating-point values. Note: To initialize a float variable, use the suffix f or F. Signed 32-bit integer Unsigned 32-bit integer Signed 64-bit integer Unsigned 64-bit integer

byte sbyte char

System.Byte System.SByte System.Char

decimal

System.Decimal

double

System.Double

float

System.Single

int uint long ulong object short

System.Int32 System.UInt32 System.Int64 System.UInt64 System.Object System.Int16

Signed 16-bit integer

Sikkim Manipal University

Page No. 38

DOT Net Technologies

Unit 2

ushort string

System.UInt16 System.String

Unsigned 16-bit integer Represents a sequence of zero or more Unicode characters. An alias for String in the .NET Framework. Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive.

Note: 1. All types in the table, except object and string, are referred to as simple types. 2. The C# type keywords and their aliases are interchangeable. 3. To display the actual type for any C# type, use the system method GetType(). For example, the following statement displays the system alias that represents the type of myVariable:

2. Integral Types:
Type sbyte byte char short ushort int uint long ulong Range -128 to 127 0 to 255 U+0000 to U+ffff -32,768 to 32,767 0 to 65,535 -2,147,483,648 to 2,147,483,647 0 to 4,294,967,295 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 0 to 18,446,744,073,709,551,615

Sikkim Manipal University

Page No. 39

DOT Net Technologies

Unit 2

3. Floating-Point Types The following table shows the precision and approximate ranges for the floating-point types.
Type float double Approximate range 1.5e45 to 3.4e38 5.0e324 to 1.7e308 Precision 7 digits 15-16 digits

Reference Types Variables of reference types, referred to as objects, store references to the actual data. This section introduces the following keywords used to declare reference types: class interface delegate This section also introduces the following built-in reference types: object string 1. class Classes are declared using the keyword class. Unlike C++, only single inheritance is allowed in C#, i.e. a class can inherit implementation from one base class only. However, a class can implement more than one interface. The following table shows examples of class inheritance and interface implementation:
Inheritance None Single None, implements two interfaces Single, implements one interface Example Class ClassA() Class DerivedClass: BaseClass { } Class ImplClass: IFace1, IFace2 { } Class ImplDerivedClass: BaseClass, IFace1 { }

Sikkim Manipal University

Page No. 40

DOT Net Technologies

Unit 2

The access levels protected and private are only allowed on nested classes. You can also declare generic classes that have type parameters. Access Modifiers: Keywords used to specify the declared accessibility of a member or a type. This following are the Four Access Modifiers: Public Protected Internal Private The following Five Accessibility Levels can be specified using the access modifiers: 1. Public: Access is not restricted. 2. Protected: Access is limited to the containing class or types derived from the containing class. 3. Internal: Access is limited to the current assembly. 4. Protected Internal: Access is limited to the current assembly or types derived from the containing class. 5. Private: Access is limited to the containing type. Generic Classes: Encapsulate operations that are not specific to a particular data type. The most common use for generic classes is with collections like linked lists, hash tables, stacks, queues, trees, and so on. Operations such as adding and removing items from the collection are performed in basically the same way regardless of the type of data being stored. For most scenarios that require collection classes, the recommended approach is to use the ones provided in the .NET Framework class library. Typically, you create generic classes by starting with an existing concrete class, and changing types into type parameters one at a time until you reach the optimal balance of generalization and usability.
Sikkim Manipal University Page No. 41

DOT Net Technologies

Unit 2

2. Interfaces: An interface contains only the signatures of methods, delegates or events. The implementation of the methods is done in the class that implements the interface, as shown in the following example:

An interface can be a member of a namespace or a class and can contain signatures of the following members:

Methods Properties Indexers Events

An interface can inherit from one or more base interfaces. When a base type list contains a base class and interfaces, the base class must come first in the list. A class that implements an interface can explicitly implement members of that interface. An explicitly implemented member cannot be accessed through a class instance, but only through an instance of the interface.
Sikkim Manipal University Page No. 42

DOT Net Technologies

Unit 2

3. The Delegate Data Type This keyword is used to declare a reference type that can be used to encapsulate a named or an anonymous method. Features of Delegate: Delegates are similar to function pointers in C++. Delegates are type-safe and secure. Delegates are the basis for Events. The declaration syntax of a delegate type is as follows:

A delegate can be instantiated by associating it either with a named or anonymous method. For more information, see Named Methods and Anonymous Methods. For use with named methods, the delegate must be instantiated with a method that has an acceptable signature. For use with anonymous methods, the delegate and the code to be associated with it are declared together. A delegate is a type that refers to a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be invoked like any other method, with parameters and a return value, as in this example:

Any method from any accessible class or struct that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate. The method can be either static or an instance method. This makes it possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the signature of the delegate, you can assign your own delegated method.

Sikkim Manipal University

Page No. 43

DOT Net Technologies

Unit 2

This ability to refer to a method as a parameter makes delegates ideal for defining callback methods. For example, a sort algorithm could be passed a reference to the method that compares two objects. Separating the comparison code allows for the algorithm to be written in a more general way.

Sikkim Manipal University

Page No. 44

DOT Net Technologies

Unit 2

4. The Object Data Type The object type is an alias for Object in the .NET Framework. In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object. You can assign values of any type to variables of type object. When a variable of a value type is converted to object, it is said to be boxed. When a variable of type object is converted to a value type, it is said to be unboxed. Example The following sample shows how variables of type object can accept values of any data type and how variables of type object can use methods on Object from the .NET Framework.

Sikkim Manipal University

Page No. 45

DOT Net Technologies

Unit 2

5. The Array Data Type An array is a data structure that contains several variables of the same type. Arrays are declared with a type:

The following examples create single-dimensional, multidimensional, and jagged arrays:

An array has the following properties:


An array can be Single-Dimensional, Multidimensional or Jagged. The default value of numeric array elements are set to zero, and reference elements are set to null.

A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.

Arrays are zero indexed: an array with n elements is indexed from 0 to n-1.

Array elements can be of any type, including an array type.


Page No. 46

Sikkim Manipal University

DOT Net Technologies

Unit 2

Array types are reference types derived from the abstract base type Array. Since this type implements IEnumerable and IEnumerable(T), you can use foreach iteration on all arrays in C#.

6. The string Data type The string type represents a sequence of zero or more Unicode characters. string is an alias for String in the .NET Framework. Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive. For example:

This displays "True" and then "False" because the content of the strings are equivalent, but a and b do not refer to the same string instance. The + operator concatenates strings:

This creates a string object that contains "good morning". Strings are immutable -- the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and the variable b continues to hold "h".

Sikkim Manipal University

Page No. 47

DOT Net Technologies

Unit 2

The [] operator can be used to access individual characters of a string:

String literals are of type string and can be written in two forms, quoted and @-quoted. Quoted string literals are enclosed in double quotation marks ("):

String literals can contain any character literal. Escape sequences are included:

This string contains a backslash, the letter f, and new line.

@-quoted string literals start with @ and are also enclosed in double quotation marks. For example:

The advantage of @-quoting is that escape sequences are not processed, which makes it easy to write, for example, a fully qualified file name:

To include a double quotation mark in an @-quoted string, double it:

Sikkim Manipal University

Page No. 48

DOT Net Technologies

Unit 2

Another use of the @ symbol is to use referenced (/reference) identifiers that are C# keywords.

2.4 Control Statements


A statement is a procedural building-block that helps in constructing programs. A statement can be used to: Declare a local variable or constant, Call a method, Create an object, or Assign a value to a variable, property, or field.

Control Statements: The control statements can be used to: Create looping structures (For Example a for loop, a dowhile loop and so on). Make a decision and branch to a new block of code

Statements are usually terminated by a semicolon. A series of statements surrounded by curly braces form a block of code; for example, a set of statements written inside a procedure or function.

Sikkim Manipal University

Page No. 49

DOT Net Technologies

Unit 2

These code blocks often follow a control statement. Variables or constants declared within a code block are only available to statements within the same code block. Example: The following code shows a method block and a code block following a control statement:

Statements in C# (or any language like C, Java, etc.) contain expressions. An expression in C# is a: Fragment of code containing a literal value, A simple name, or An operator and its operands.

Most common expressions, when evaluated, yield a literal value, a variable, or an object property or object indexer access. Whenever a variable, object property or object indexer access is identified from an expression, the value of that item is used as the value of the expression. In C#, an expression can be placed anywhere that a value or object is required as long as the expression ultimately evaluates to the required type. The if Statement It selects a statement for execution based on the value of a Boolean expression.

Sikkim Manipal University

Page No. 50

DOT Net Technologies

Unit 2

Example: A Boolean flag f1 is set to true and checked in the if statement.

To execute more than one statement, multiple statements can be conditionally executed by including them into blocks using {}. Example 1: The user enters a character from the keyboard and the program checks if the input character is an alphabetic character. If so, it checks if it is lowercase or uppercase. In each case, the proper message is displayed.

Sikkim Manipal University

Page No. 51

DOT Net Technologies

Unit 2

The if else Statement

The steps used to carry out the execution of if statements are as follows: 1. The Boolean expression the if statement depends on is first evaluated. 2. If the Boolean expression evaluates to true, control is transferred to the first embedded statement(s). If the control reaches the end point of that statement, control is transferred to the end point of the entire if statement. 3. If the Boolean expression evaluates to false and an else clause is present, control is transferred to the second embedded statement(s). If the control reaches the end point of that statement, control is transferred to the end point of the entire if statement. 4. If the Boolean expression evaluates to false and an else clause is not present, control is transferred to the end point of the entire if statement. The switch-case Statement The switch statement selects a statement list for execution that has a switch label that corresponds to the value of the switch expression.
Sikkim Manipal University Page No. 52

DOT Net Technologies

Unit 2

This statement is a substitute for multiple if statements. Control is transferred to the case statement which matches the value of the switch. The switch statement can include any number of case instances, but no two case statements can have the same value. Execution of the statement body begins at the selected statement and proceeds until the break statement transfers control out of the case body. A jump statement such as a break is required after each case block, including the last block whether it is a case statement or a default statement. With one exception, (unlike the C++ switch statement), C# does not support an implicit fall through from one case label to another. The one exception is if a case statement has no code. If no case expression matches the switch value, then control is transferred to the statement(s) that follow the optional default label. If there is no default label, control is transferred outside the switch. The for Statement The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false. The for loop is useful for iterating over arrays and for sequential processing.

Sikkim Manipal University

Page No. 53

DOT Net Technologies

Unit 2

In the following example, the value of int i is written to the console and i is incremented every time through the loop by 1.

Example of for statement

All of the expressions of the for statement are optional; The while Statement The while statement executes a statement or a block of statements until a specified expression evaluates to false.

Sikkim Manipal University

Page No. 54

DOT Net Technologies

Unit 2

The do while Statement The do statement executes a statement or a block of statements enclosed in {} repeatedly until a specified expression evaluates to false. Example: In the following example the do-while loop statements execute as long as the variable y is less than 5.

The break Statement The break statement terminates the closest enclosing loop or switch statement in which it appears. Control is passed to the statement that follows the terminated statement, if any. Example In this example, the conditional statement contains a counter that is supposed to count from 1 to 100; however, the break statement terminates the loop after 4 counts

Sikkim Manipal University

Page No. 55

DOT Net Technologies

Unit 2

2.4.8 The continue Statement The continue statement passes control to the next iteration of the enclosing iteration statement in which it appears. Example In this example, a counter is initialized to count from 1 to 10. By using the continue statement in conjunction with the expression (i < 9), the statements between continue and the end of the for body are skipped.

The return Statement The return statement terminates execution of the method in which it appears and returns control to the calling method. It can also return an optional value. If the method is a void type, the return statement can be omitted.

2.5 Understanding Properties & Indexes


Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.
Sikkim Manipal University Page No. 56

DOT Net Technologies

Unit 2

In this example, the TimePeriod class stores a time period. Internally the class stores the time in seconds, but a property named Hours enables a client to specify a time in hours. The accessors for the Hours property perform the conversion between hours and seconds.
class TimePeriod { private double seconds;

public double Hours { get { return seconds / 3600; } set { seconds = value * 3600; } } } class Program { static void Main() { TimePeriod t = new TimePeriod(); // Assigning the Hours property causes the 'set' accessor to be called. t.Hours = 24; // Evaluating the Hours property causes the 'get' accessor to be called. System.Console.WriteLine("Time in hours: " + t.Hours); } }

Output Time in hours: 24 Properties Overview

Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.

A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels.

Sikkim Manipal University

Page No. 57

DOT Net Technologies

Unit 2

The value keyword is used to define the value being assigned by the set indexer.

Properties that do not implement a set method are read only.

Using Properties Properties combine aspects of both fields and methods. To the user of an object, a property appears to be a field, accessing the property requires the same syntax. To the implementer of a class, a property is one or two code blocks, representing a get accessor and/or a set accessor. The code block for the get accessor is executed when the property is read; the code block for the set accessor is executed when the property is assigned a new value. A property without a set accessor is considered read-only. A property without a get accessor is considered write-only. A property that has both accessors is read-write. Unlike fields, properties are not classified as variables. Therefore, you cannot pass a property as a ref (C# Reference) or out (C# Reference) parameter. Properties have many uses: they can validate data before allowing a change; they can transparently expose data on a class where that data is actually retrieved from some other source, such as a database; they can take an action when data is changed, such as raising an event, or changing the value of other fields. Properties are declared in the class block by specifying the access level of the field, followed by the type of the property, followed by the name of the property, and followed by a code block that declares a get-accessor and/or a set accessor.

Sikkim Manipal University

Page No. 58

DOT Net Technologies

Unit 2

Example
public class Date { private int month = 7; //"backing store" public int Month { get { return month; } set { if ((value > 0) && (value < 13)) { month = value; } } } }

In this example, Month is declared as a property so that the set accessor can make sure that the Month value is set between 1 and 12. The Month property uses a private field to track the actual value. The real location of a property's data is often referred to as the property's "backing store." It is common for properties to use private fields as a backing store. The field is marked private in order to make sure that it can only be changed by calling the property. The get Accessor The body of the get accessor resembles that of a method. It must return a value of the property type. The execution of the get accessor is equivalent to reading the value of the field. For example, when you are returning the private variable from the get accessor and optimizations are enabled, the call to the get accessor method is in lined by the compiler so there is no method-call overhead. However, a virtual get accessor method cannot be in lined because the compiler does not know at compile-time which method
Sikkim Manipal University Page No. 59

DOT Net Technologies

Unit 2

may actually be called at run time. The following is a get accessor that returns the value of a private field name:
class Person { private string name; // the name field public string Name // the Name property { get { return name; } } }

When you reference the property, except as the target of an assignment, the get accessor is invoked to read the value of the property. Example:
Person p1 = new Person(); //... System.Console.Write(p1.Name); // the get accessor is invoked here

The get accessor must end in a return or throw statement, and control cannot flow off the accessor body. It is a bad programming style to change the state of the object by using the get accessor. Example: The following accessor produces the side effect of changing the state of the object every time that the number field is accessed.
private int number; public int Number { get { return number++; // Don't do this } } Sikkim Manipal University Page No. 60

DOT Net Technologies

Unit 2

The get accessor can be used to return the field value or to compute it and return it. Example:
class Employee { private string name; public string Name { get { return name != null ? name : "NA"; } } }

In the previous code segment, if you do not assign a value to the Name property, it will return the value NA. Set Accessor The set accessor resembles a method whose return type is void. It uses an implicit parameter called value, whose type is the type of the property. In the following example, a set accessor is added to the Name property:
class Person { private string name; // the name field public string Name // the Name property { get { return name; } set { name = value; } } }

Sikkim Manipal University

Page No. 61

DOT Net Technologies

Unit 2

When you assign a value to the property, the set accessor is invoked by using an argument that provides the new value. Example
Person p1 = new Person(); p1.Name = "Joe"; // the set accessor is invoked here System.Console.Write(p1.Name); // the get accessor is invoked here

It is an error to use the implicit parameter name, value, for a local variable declaration in a set accessor.

2.6 Using Delegates and Events


An event is a message sent by an object to signal the occurrence of an action. The action could be caused by user interaction, such as a mouse click, or it could be triggered by some other program logic. The object that raises the event is called the event sender. The object that captures the event and responds to it is called the event receiver. In event communication, the event sender class does not know which object or method will receive (handle) the events it raises. What is needed is an intermediary (or pointer-like mechanism) between the source and the receiver. The .NET Framework defines a special type (Delegate) that provides the functionality of a function pointer. A delegate is a class that can hold a reference to a method. Unlike other classes, a delegate class has a signature, and it can hold references only to methods that match its signature. A delegate is thus equivalent to a typesafe function pointer or a callback. While delegates have other uses, the discussion here focuses on the event handling functionality of delegates. A delegate declaration is sufficient to define a delegate class. The declaration supplies the signature of the delegate, and the common language runtime

Sikkim Manipal University

Page No. 62

DOT Net Technologies

Unit 2

provides the implementation. The following example shows an event delegate declaration.

The syntax is similar to that of a method declaration; however, the delegate keyword informs the compiler that AlarmEventHandler is a delegate type. By convention, event delegates in the .NET Framework have two parameters, the source that raised the event and the data for the event. An instance of the AlarmEventHandler delegate can bind to any method that matches its signature, such as the AlarmRang method of the WakeMeUp class shown in the following example.
C# Code public class WakeMeUp { // AlarmRang has the same signature as AlarmEventHandler. public void AlarmRang(object sender, AlarmEventArgs e) {...}; ... }

Custom event delegates are needed only when an event generates event data. Many events, including some user-interface events such as mouse clicks, do not generate event data. In such situations, the event delegate provided in the class library for the no-data event, System.EventHandler, is adequate. Its declaration follows.

C# Code
delegate void EventHandler(object sender, EventArgs e); Event delegates are multicast, which means that they can hold references to more than one event handling method. Delegates allow for flexibility and fine-grain control in event handling. A delegate acts as an event dispatcher
Sikkim Manipal University Page No. 63

DOT Net Technologies

Unit 2

for the class that raises the event by maintaining a list of registered event handlers for the event.

Using Delegates
A delegate is a type that safely encapsulates a method, similar to a function pointer in C and C++. Unlike C function pointers, delegates are objectoriented, type safe, and secure. The type of a delegate is defined by the name of the delegate. The following example declares a delegate named Del that can encapsulate a method that takes a string as an argument and returns void:

C# Code
public delegate void Del(string message);

A delegate object is normally constructed by providing the name of the method the delegate will wrap, or with an anonymous Method. Once a delegate is instantiated, a method call made to the delegate will be passed by the delegate to that method. The parameters passed to the delegate by the caller are passed to the method, and the return value, if any, from the method is returned to the caller by the delegate. This is known as invoking the delegate. An instantiated delegate can be invoked as if it were the wrapped method itself. For example:
C# Code // Create a method for a delegate. public static void DelegateMethod(string message) { System.Console.WriteLine(message); } // Instantiate the delegate. Del handler = DelegateMethod; // Call the delegate. handler("Hello World");

Sikkim Manipal University

Page No. 64

DOT Net Technologies

Unit 2

Delegate types are derived from the Delegate class in the .NET Framework. Delegate types are sealed they cannot be derived from and it is not possible to derive custom classes from Delegate. Because the instantiated delegate is an object, it can be passed as a parameter, or assigned to a property. This allows a method to accept a delegate as a parameter, and call the delegate at some later time. This is known as an asynchronous callback, and is a common method of notifying a caller when a long process has completed. When a delegate is used in this fashion, the code using the delegate does not need any knowledge of the implementation of the method being used. The functionality is similar to the encapsulation interfaces provide. Another common use of callbacks is defining a custom comparison method and passing that delegate to a sort method. It allows the caller's code to become part of the sort algorithm. The following example method uses the Del type as a parameter:
C# Code public void MethodWithCallback(int param1, int param2, Del callback) { callback("The number is: " + (param1 + param2).ToString()); }

You can then pass the delegate created above to that method:
C# Code MethodWithCallback(1, 2, handler);

and receive the following output to the console: The number is: 3 Using the delegate as an abstraction, MethodWithCallback does not need to call the console directly it does not have to be designed with a console in mind. What MethodWithCallback does is simply prepare a string and pass

Sikkim Manipal University

Page No. 65

DOT Net Technologies

Unit 2

the string to another method. This is especially powerful since a delegated method can use any number of parameters. When a delegate is constructed to wrap an instance method, the delegate references both the instance and the method. A delegate has no knowledge of the instance type aside from the method it wraps, so a delegate can refer to any type of object as long as there is a method on that object that matches the delegate signature. When a delegate is constructed to wrap a static method, it only references the method. Consider the following declarations: C# Code public class MethodClass { public void Method1(string message) { } public void Method2(string message) { } } Along with the static DelegateMethod shown previously, we now have three methods that can be wrapped by a Del instance. A delegate can call more than one method when invoked. This is referred to as multicasting. To add an extra method to the delegate's list of methods the invocation list simply requires adding two delegates using the addition or addition assignment operators ('+' or '+='). For example:
C# Code MethodClass obj = new MethodClass(); Del d1 = obj.Method1; Del d2 = obj.Method2; Del d3 = DelegateMethod; //Both types of assignment are valid. Del allMethodsDelegate = d1 + d2; allMethodsDelegate += d3;

Sikkim Manipal University

Page No. 66

DOT Net Technologies

Unit 2

At this point allMethodsDelegate contains three methods in its invocation list Method1, Method2, and DelegateMethod. The original three delegates, d1, d2, and d3, remain unchanged. When allMethodsDelegate is invoked, all three methods are called in order. If the delegate uses reference parameters, the reference is passed sequentially to each of the three methods in turn, and any changes by one method are visible to the next method. When any of the methods throws an exception that is not caught within the method, that exception is passed to the caller of the delegate and no subsequent methods in the invocation list are called. If the delegate has a return value and/or out parameters, it returns the return value and parameters of the last method invoked. To remove a method from the invocation list, use the decrement or decrement assignment operator ('-' or '='). For example: C# Code //remove Method1 allMethodsDelegate -= d1; // copy AllMethodsDelegate while removing d2 Del oneMethodDelegate = allMethodsDelegate - d2; Because delegate types are derived from System.Delegate, the methods and properties defined by that class can be called on the delegate. For example, to find the number of methods in a delegate's invocation list, you may write: C# Code int invocationCount = d1.GetInvocationList().GetLength(0); Delegates with more than one method in their invocation list derive from MulticastDelegate, which is a subclass of System.Delegate. The above code works in either case because both classes support GetInvocationList.
Sikkim Manipal University Page No. 67

DOT Net Technologies

Unit 2

Multicast delegates are used extensively in event handling. Event source objects send event notifications to recipient objects that have registered to receive that event. To register for an event, the recipient creates a method designed to handle the event, then creates a delegate for that method and passes the delegate to the event source. The source calls the delegate when the event occurs. The delegate then calls the event handling method on the recipient, delivering the event data. The delegate type for a given event is defined by the event source. Comparing delegates of two different types assigned at compile-time will result in a compilation error. If the delegate instances are statically of the type System.Delegate, then the comparison is allowed, but will return false at run time. For example:
C# Code delegate void Delegate1(); delegate void Delegate2(); static void method(Delegate1 d, Delegate2 e, System.Delegate f) { // Compile-time error. //Console.WriteLine(d == e); // OK at compile-time. False if the run-time type of f //is not the same as that of d. System.Console.WriteLine(d == f); }

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
Sikkim Manipal University Page No. 68

DOT Net Technologies

Unit 2

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 called. 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. In the .NET Framework class library, events are based on the EventHandler delegate and the EventArgs base class.

2.7 Exception Handling


C#, like many object-oriented languages, handles errors and abnormal conditions with exceptions. An exception is an object that encapsulates information about an unusual program occurrence. It is important to distinguish between bugs, errors, and exceptions. A bug is a programmer mistake that should be fixed before the code is shipped. Exceptions are not a protection against bugs. Although a bug might cause an exception to be thrown, you should not rely on exceptions to handle your bugs. Rather, you should fix the bug.
Sikkim Manipal University Page No. 69

DOT Net Technologies

Unit 2

An error is caused by user action. For example, the user might enter a number where a letter is expected. Once again, an error might cause an exception, but you can prevent that by catching errors with validation code. Whenever possible, errors should be anticipated and prevented. Even if you remove all bugs and anticipate all user errors, you will still run into predictable but unpreventable problems, such as running out of memory or attempting to open a file that no longer exists. You cannot prevent exceptions, but you can handle them so that they do not bring down your program. When your program encounters an exceptional circumstance, such as running out of memory, it throws (or "raises") an exception. When an exception is thrown, execution of the current function halts and the stack is unwound until an appropriate exception handler is found. This means that if the currently running function does not handle the exception, the current function will terminate and the calling function will get a chance to handle the exception. If none of the calling functions handles it, the exception will ultimately be handled by the CLR, which will abruptly terminate your program. An Exception Handler is a block of code designed to handle the exception you've thrown. Exception handlers are implemented as catch statements. Ideally, if the exception is caught and handled, the program can fix the problem and continue. Even if your program can't continue, by catching the exception you have an opportunity to print a meaningful error message and terminate gracefully. If there is code in your function that must run regardless of whether an exception is encountered (e.g., to release resources you've allocated), you can place that code in a finally block, where it is certain to run, even in the presence of exceptions.
Sikkim Manipal University Page No. 70

DOT Net Technologies

Unit 2

Throwing and Catching Exceptions In C#, you can throw only objects of type System.Exception, or objects derived from that type. The CLR System namespace includes a number of exception types that can be used by your program. These exception types include ArgumentNullException, InvalidCastException, and

OverflowException, as well as many others. The throw Statement To signal an abnormal condition in a C# class, you throw an exception. To do this, use the keyword throw. This line of code creates a new instance of System.Exception and then throws it: C# Code throw new System.Exception( ); Throwing an exception immediately halts execution while the CLR searches for an exception handler. If an exception handler cannot be found in the current method, the runtime unwinds the stack, popping up through the calling methods until a handler is found. If the runtime returns all the way through Main( ) without finding a handler, it terminates the program.
Example: Throwing an Exception using System; public class Test { public static void Main( ) { Console.WriteLine("Enter Main..."); Test t = new Test( ); t.Func1( ); Console.WriteLine("Exit Main..."); }

Sikkim Manipal University

Page No. 71

DOT Net Technologies

Unit 2

Example: Continued
public void Func1( ) { Console.WriteLine("Enter Func1..."); Func2( ); Console.WriteLine("Exit Func1..."); } public void Func2( ) { Console.WriteLine("Enter Func2..."); throw new System.Exception( ); Console.WriteLine("Exit Func2..."); } } Output: Enter Main... Enter Func1... Enter Func2... Exception occurred: System.Exception: An exception of type System.Exception was thrown. at Programming_CSharp.Test.Func2( ) in ...exceptions01.cs:line 26 at Programming_CSharp.Test.Func1( ) in ...exceptions01.cs:line 20 at Programming_CSharp.Test.Main( ) in ...exceptions01.cs:line 12 This simple example writes to the console as it enters and exits each method. Main( ) creates an instance of type Test and call Func1( ). After printing out the Enter Func1 message, Func1( ) immediately calls Func2( ). Func2( ) prints out the first message and throws an object of type System.Exception. Execution immediately stops, and the CLR looks to see if there is a handler in Func2( ).
Sikkim Manipal University Page No. 72

DOT Net Technologies

Unit 2

There is not, and so the runtime unwinds the stack (never printing the exit statement) to Func1( ). Again, there is no handler, and the runtime unwinds the stack back to Main( ). With no exception handler there, the default handler is called, which prints the error message. The catch Statement In C#, an exception handler is called a catch block and is created with the catch keyword. In the example given below, the throw statement is executed within a try block, and a catch block is used to announce that the error has been handled. using System; public class Test { public static void Main( ) { Console.WriteLine("Enter Main..."); Test t = new Test( ); t.Func1( ); Console.WriteLine("Exit Main..."); } public void Func1( ) { Console.WriteLine("Enter Func1..."); Func2( ); Console.WriteLine("Exit Func1..."); }

Sikkim Manipal University

Page No. 73

DOT Net Technologies

Unit 2

public void Func2( ) { Console.WriteLine("Enter Func2..."); try { Console.WriteLine("Entering try block..."); throw new System.Exception( ); Console.WriteLine("Exiting try block..."); } catch { Console.WriteLine( "Exception caught and handled."); } Console.WriteLine("Exit Func2..."); } } Output: Enter Main... Enter Func1... Enter Func2... Entering try block... Exception caught and handled. Exit Func2... Exit Func1... Exit Main...

You would typically put the try block around a potentially "dangerous" statement, such as accessing a file, allocating memory, and so forth. Following the try statement is a generic catch statement. The catch statement is generic because you haven't specified what kind of exceptions to catch. In this case, the statement will catch any exceptions that are thrown.

Sikkim Manipal University

Page No. 74

DOT Net Technologies

Unit 2

Taking Corrective Action In the above example, the catch statement simply reports that the exception has been caught and handled. In a real-world example, you might take corrective action to fix the problem that caused an exception to be thrown. For example, if the user is trying to open a read-only file, you might invoke a method that allows the user to change the attributes of the file. If the program has run out of memory, you might give the user an opportunity to close other applications. If all others fail, the catch block can print an error message so that the user come to know what had gone wrong. Unwinding the call stack Examine the output of Example above carefully. You see the code enter Main( ), Func1( ), Func2( ), and the try block. You never see it exit the try block, though it does exit Func2( ), Func1( ), and Main( ). What happened? When the exception is thrown, execution halts immediately and is handed to the catch block. It never returns to the original code path. It never gets to the line that prints the exit statement for the try block. The catch block handles the error, and then execution falls through to the code following catch. Without catch the call stack unwinds, but with catch it does not unwind as a result of the exception. The exception is now handled; there are no more problems and the program continues. This becomes a bit clearer if you move the try/catch blocks up to Func1( ), as shown in Example below:

Sikkim Manipal University

Page No. 75

DOT Net Technologies

Unit 2

using System; public class Test { public static void Main( ) { Console.WriteLine("Enter Main..."); Test t = new Test( ); t.Func1( ); Console.WriteLine("Exit Main..."); } public void Func1( ) { Console.WriteLine("Enter Func1..."); try { Console.WriteLine("Entering try block..."); Func2( ); Console.WriteLine("Exiting try block..."); } catch { Console.WriteLine( "Exception caught and handled."); } Console.WriteLine("Exit Func1..."); }

public void Func2( ) { Console.WriteLine("Enter Func2..."); throw new System.Exception( ); Console.WriteLine("Exit Func2..."); } } Output: Enter Main... Enter Func1... Entering try block... Enter Func2... Exception caught and handled. Exit Func1... Exit Main...

Sikkim Manipal University

Page No. 76

DOT Net Technologies

Unit 2

This time the exception is not handled in Func2( ); it is handled in Func1( ). When Func2( ) is called, it prints the Enter statement and then throws an exception. Execution halts and the runtime looks for a handler, but there isn't one. The stack unwinds, and the runtime finds a handler in Func1( ). The catch statement is called, and execution resumes immediately following the catch statement, printing the Exit statement for Func1( ) and then for Main( ). Make sure you are comfortable with why the Exiting Try Block statement and the Exit Func2 statement are not printed. This is a classic case where putting the code into a debugger and then stepping through it can make things very clear. Creating dedicated catch statements So far, you've been working only with generic catch statements. You can create dedicated catch statements that handle only some exceptions and not others, based on the type of exception thrown. Example below illustrates how to specify which exception you'd like to handle. using System; public class Test { public static void Main( ) { Test t = new Test( ); t.TestFunc( ); } // try to divide two numbers // handle possible exceptions

Sikkim Manipal University

Page No. 77

DOT Net Technologies

Unit 2

public void TestFunc( ) { try { double a = 5; double b = 0; Console.WriteLine ("{0} / {1} = {2}", a, b, DoDivide(a,b)); } // most derived exception type first catch (System.DivideByZeroException) { Console.WriteLine( "DivideByZeroException caught!"); } catch (System.ArithmeticException) { Console.WriteLine( "ArithmeticException caught!"); } // generic exception type last catch { Console.WriteLine("Unknown exception caught"); } } // do the division if legal public double DoDivide(double a, double b) { if (b == 0) throw new System.DivideByZeroException( ); if (a == 0) throw new System.ArithmeticException( ); return a/b; } } } Output: DivideByZeroException caught!

In this example, the DoDivide( ) method will not let you divide zero by another number, nor will it let you divide a number by zero. It throws an instance of DivideByZeroException if you try to divide by zero. If you try to divide zero by another number, there is no appropriate exception -- dividing zero by another number is a legal mathematical operation and shouldn't
Sikkim Manipal University Page No. 78

DOT Net Technologies

Unit 2

throw an exception at all. For the sake of this example, assume you don't want to allow division by zero; you will throw an ArithmeticException. When the exception is thrown, the runtime examines each exception handler in order and matches the first one it can. When you run this with a=5 and b=7, the output is: 5 / 7 = 0.7142857142857143 As you'd expect, no exception is thrown. However, when you change the value of a to 0, the output is: ArithmeticException caught! The exception is thrown, and the runtime examines the first exception, DivideByZeroException. Because this does not match, it goes on to the next handler, ArithmeticException, which does match. In a final pass through, suppose you change a to 7 and b to 0. This throws the DivideByZeroException. It is possible to distribute your try/catch statements, catching some specific exceptions in one function and more generic exceptions in higher, calling functions. Your design goals should dictate the exact design. Assume you have a method A that calls another method B, which in turn calls method C. Method C calls method D, which then calls method E. Method E is deep in your code; methods B and A are higher up. If you anticipate that method E might throw an exception, you should create a try/catch block deep in your code to catch that exception as close as possible to the place where the problem arises. You might also want to create more general exception handlers higher up in the code in case unanticipated exceptions slip by.

The finally Statement


In some instances, throwing an exception and unwinding the stack can create a problem. For example, if you have opened a file or otherwise committed a resource, you might need an opportunity to close the file or flush the buffer.

Sikkim Manipal University

Page No. 79

DOT Net Technologies

Unit 2

In the event, however, that there is some action you must take regardless of whether an exception is thrown, such as closing a file, you have two strategies to choose from. One approach is to enclose the dangerous action in a try block and then to close the file in both the catch and try blocks. However, this is an ugly duplication of code, and it's error prone. C# provides a better alternative in the finally block. The code in the finally block is guaranteed to be executed regardless of whether an exception is thrown. The TestFunc( ) method in Example below simulates opening a file as its first action. The method undertakes some mathematical operations, and the file is closed. It is possible that some time between opening and closing the file an exception will be thrown. If this were to occur, it would be possible for the file to remain open. The developer knows that no matter what happens, at the end of this method the file should be closed, so the file close function call is moved to a finally block, where it will be executed regardless of whether an exception is thrown.

Sikkim Manipal University

Page No. 80

DOT Net Technologies

Unit 2

catch { Console.WriteLine("Unknown exception caught"); } finally { Console.WriteLine ("Close file here."); }}}} // do the division if legal public double DoDivide(double a, double b) { if (b == 0) throw new System.DivideByZeroException( ); if (a == 0) throw new System.ArithmeticException( ); return a/b; } Output: Open file here DivideByZeroException caught! Close file here. Output when b = 12: Open file here 5 / 12 = 0.416666666666667 This line may or may not print Close file here.

In this example, one of the catch blocks has been eliminated to save space and a finally block has been added. Whether or not an exception is thrown, the finally block is executed, and so in both output examples you see the message: Close file here.

2.8 Summary
This unit makes the user familiar with the Microsoft language developed especially for .Net Application development. It has the major features like Object-orientation, interoperability, and component development. It is a language developed on the lines of Visual Basic. It takes advantage of the Common Language Runtime of .Net environment. It takes the reader a
Sikkim Manipal University Page No. 81

DOT Net Technologies

Unit 2

walkthrough regarding the features of C# language. It shows a step-by-step approach in developing programs using C#. It introduces the data types of C# and code samples illustrating their usage. It then illustrates the control statements and their applications with respect to C# programming language. It then introduces the concept of properties and indexes, and then continues with Delegates and Events of C#. Self Assessment Questions 1. The _______ language is an Object Oriented Programming Language developed by Microsoft to become a key part of their .Net software development platform. a) C++ b) Visual C++ c) C# d) Visual Basic.Net

2. The syntax for compiling the sample C# program is _______ 3. To run a C# executable file, the command that should be typed at the command prompt is _________ 4. The using directive references a namespace called System, provided by the ________________, a synonym for the .Net Framework. 5. Classes can also be defined as ______ by using type parameters that enable client code to customize the class in a type-safe and efficient manner. 6. A _______ modifier is used so that the method it is assigned to becomes a method of the class rather than an instance of the class. 7. The ________ directive allows the use of types in a namespace so that you do not have to qualify the use of a type in that namespace. 8. The Struct and Enumeration in C# are of _________ data types a) int b) value c) char d) string

9. Using the ______ operator calls the default constructor of the specific type and assigns the default value to the variable.

Sikkim Manipal University

Page No. 82

DOT Net Technologies

Unit 2

2.9 Terminal Questions


1. Describe the steps involved in compiling and executing a C# program. (Refer to 2.2) 2. Describe the steps involved in creating classes and objects with the help of a program in C#. (Refer to 2.2) 3. Write a program to demonstrate the usage of if statements (Refer to 2.4) 4. Write a program to demonstrate exception handling in C# (Refer to 2.7)

2.10 Answers to Self Assessment Questions


1. c 2. csc.exe <filename>.cs 3. <filename>.exe 4. Common Language Infrastructure (CLI ) 5. generic 6. static 7. using 8. b 9. new

Sikkim Manipal University

Page No. 83

Anda mungkin juga menyukai