+ All Categories
Home > Documents > C Sharp Programming SLIDES 01-FP2005-Ver1

C Sharp Programming SLIDES 01-FP2005-Ver1

Date post: 11-Apr-2015
Category:
Upload: api-3831765
View: 207 times
Download: 7 times
Share this document with a friend
82
ER/CORP/CRS/LA06/003 1 C Sharp Programming – Day 1
Transcript
Page 1: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 1

C Sharp Programming – Day 1

Page 2: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 2

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

2

Course Objectives

• To introduce the participants to C# programming and object oriented features of C#

• To understand the component oriented features of C# like indexers, properties, attributes and illustrate their usage in programs

• To introduce development of Assembly• To introduce Windows programming and delegate based event handling in C#• To understand Exception handling techniques in C#• To introduce Multithreading in C#• To introduce to Reflection• To introduce File Handling in C# • To introduce Parsing• To introduce concept of Remoting through C# programs• To introduce Windows Services• To introduce Application Deployment

Page 3: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 3

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

3

Day Wise Plan

• Day1− Recap of OO

- Data Types

- Class & Object

- Inheritance

- Namespace

- Structure

• Day 2− Interface− Assembly− Property− Indexer− Collection− Preprocessor Directives

Page 4: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 4

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

4

Day Wise Plan• Day 3

− GUI− Delegates− Unsafe Code− Exception Handling− Debugging

• Day 4− Threading− Reflection− Serialization− File Handling

• Day 5− Parsing− Remoting− Windows Services− Deployment

• Day 6 and Day 7 - Project

Page 5: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 5

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

5

References

• Tom Archer,” Inside C# “ ,WP Publications• Peter Drayton, Ben Albahari and Ted Neward, “C# in a nutshell” , O’reily

Publications• Microsoft Corporation , “Microsoft C# Language Specifications “, Microsoft

Press, New York.• Microsoft Corporation, “Developing Windows –based Applications with

Microsoft VB .Net and Visual C# .NET”,PHI Publications• Robinson, Nagel, Glynn, Skinner, Watson and Evjen, “Professional C#”, Wiley

Publications• Andrew Troelsen, “C# and the .NET Platform “, Apress, CA,USA• http://www.c-sharpcorner.com/• http://gotdotnet.com/

Page 6: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 6

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

6

Session Plan

• Recap of OO• Classes and Objects• Basic Data Types and Control structures, • Data Members and Methods of a Class (Creation of objects)• Constructors• Destructors• Garbage Collection• Static• Command Line Arguments• Inheritance• Overloading and Overriding• Abstract and Sealed• Namespaces• Structures

Page 7: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 7

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

7

Recap of Object Oriented Concepts

• Classes − templates used for defining new types. − Contains attributes and behavior

• Instance of a class is called an Object

Classes lie at the heart of every object-oriented language. A class can be defined as the encapsulation of data and the methods that work on that data.That’s true in any object oriented or object based language.

Page 8: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 8

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

8

Recap of Object Oriented Concepts

• Encapsulation− Mechanism that binds together code and the data it manipulates in a class− Data members are made private and are prevented from being accessed

by outside classes thus achieves Data Hiding

• Inheritance− Process by which one object can acquire the properties of another object. − Supports hierarchical classification

• Polymorphism-Ability of objects to respond in their own unique way to the same message

Page 9: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 9

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

9

Structure of a C# program

using System;

namespace InsideCSharp

{

class FirstProgram

{

public static void Main()

{

Console.WriteLine(“Hello World”);

}

}

}

C# is an object oriented programming language. It supports features like Garbage Collection, Versioning ,Language inter-operability and COM support. It provides benefits like web compatibility ,minimum probability of errors and reduced cost of developemnt.

Namespace is a means of semantically grouping elements such as classes to avoid name collision.System is a predefined namespace and InsideCSharp is a user defined namespace.(Namespaces will be covered later in detail).In the example , we have a single class named FirstProgram that contains a single member – a method named Main.Every C# application must define a Main method in one of its classes.The public keyword (covered later in detail) is an access modifier that tells the C# compiler that any code can call this method.The static modifier (covered later in detail) tells the compiler that the Main method is a global method and the class doesn’t need to instantiated for the method to be called.The given code shows the Main method as returning void and not receiving any arguments. However, you can define Main method to return a value and take array of arguments. (covered later in detail)

Page 10: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 10

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

10

Structure of a C# program

• The extension of a C# program is cs• There is no restriction on the filename unless it follows the naming convention

of the OS• Every statement in C# ends with ;• Main is the starting point of execution of a C# program• { } describes a block of code• Main function must be written inside the class

Console is the name of a predefined class in C#.Supports Console Input/Output.Method WriteLine of the Console class displays information on the Console.

Console I/O is accomplished through standard streams Console.In, Console.Out and Console.Error

Most of the C# applications will not be console based. Hence console based I/O is used in simple teaching applications

To read a character, method Read is to be used.To read a line of characters, method ReadLine is tobe used.

Page 11: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 11

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

11

Data Types

Assignment of one reference type to another copies the reference

Assignment of one value type to another copies the value

Allocated on heapAllocated on stack

Variable holds memory locationVariable holds the actual value

Reference types include class types, interface types, delegate types, and array types

Value types include simple types like char, int, and float, enum types, and struct types

Reference TypesValue Types

All types are objects in the CTS and they all ultimately derive from System.Object. The two main categories of types supported by the CTS : value types and reference types.

Page 12: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 12

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

12

Data Types – Value TypesData Types

Integer FloatingPoint Character Boolean

byte

sbyte

short

ushort

int

float

double

Char bool

uint

long

ulong

decimal

Unicode defines character set that is large enough to represent all human readable characters

Bool data type represents true/false only. Does not represent any equivalent numeric valuesEx: in C, a non zero value is true and 0 is false. Such a representation is not possible in C#The decimal data type uses 128 bits to represent values and used in monetary calculations. the decimal type eliminates the rounding errors that occur in various floating point calculations. the decimal type can accurately represent upto 28 decimal places.

Page 13: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 13

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

13

Data Types – Value Types

Character – 16 bit (uses Unicode)char

1E-28 to 7.9E+28Numeric type for financial calculations – 128 bits (supports upto 28 decimal places)

decimal

5E-324 to 1.7E+308Double precision floating point – 64 bitsdouble

1.5E-45 to 3.4E+38Single precision floating point – 32 bitsfloat

0 to 18,446,744,073,709,551,615Unsigned long integer – 64 bitsulong

-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Long integer – 64 bitslong

0 to 4,294,967,295Unsigned integer – 32 bitsuint

-2,147,483,648 to 2,147,483,647Integer – 32 bitsint

0 to 65535Unsigned short integer – 16 bitsushort

-32,768 to +32,767Short integer – 16 bitsshort

-128 to 1278 bit signed integersbyte

0 to 2558 bit unsigned integerbyte

Represents true/falsebool

RangeDescriptionData Type

Page 14: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 14

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

14

Variables – Value Types

• Declaration syntax of a variable in C#:<data type> <name of variable>

Ex:

int iNum;

• Initializing variables:Ex:

int iNum = 10;

Variables in C# can be declared anywhere before referencing them.

The scope of the variable is from the declaration till the end of the block in which it is declared.

Page 15: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 15

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

15

What is the output of the following program?

using System;

class Test

{

public static void Main()

{

int iNum = 10;

{

int iNum = 100;

Console.WriteLine(iNum);

}

Console.WriteLine(iNum);

}

}

ERROR

The variable iNum is still in scope in the inner block

To display data in a formatted way, use the following form of WriteLine:Ex: WriteLine("format string", arg0, arg1, arg2 ...., argN);The format string is of the form:{argnum, width:fmt}Ex: Console.WriteLine("LC is for {0} days",88);The output is: LC is for 88 days.In place of {0}, the value 88 is displayed.Ex: specifying the field width:Console.WriteLine("LC is {0,10} and SC is {1,5} days",88,49);The output of the above statement is:LC is 88 days and SC is 49 daysobserve that spaces are added to fill in the unused fields.

Page 16: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 16

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

16

This slide has been intentionally left blank : Notes Page Contd.

Ex: Format specifiers like \t can be used.Console.WriteLine("{0}\t{1}\t",0,1);The output is:0 1Ex: Console.WriteLine("value of 10/3: {0,#.##}",10.0/3);The output is displayed upto 2 decimal placesvalue of 10/3: 3.33Ex: Console.WriteLine("value is: {0,###,###.##}",123456.78);The output is:value is: 123,456.78Ex: To display the currency - use C format specifierConsole.WriteLine("Amount is: {0:C}",1234);The output is:Amount is: $1234

Page 17: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 17

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

17

C# is a strongly typed language

• Automatic conversions (or widening conversions) from one type to another takes place if:− the source and the destination types are compatible− the destination type is larger than the source typeAutomatic conversions in C# does not happen that leads to data loss.

• Explicit conversions require type casting.

int iVal = 1234;

long lVal = iVal;

double dVal = 34.23;

float fVal = dVal;

long lVal = 23456;

int iVal = (int) lVal;

This implicit conversion does not lead to data loss

The above statement does not compile as conversion from double to float leads to data loss.

This is an example of explicit conversion

Page 18: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 18

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

18

Literals – Value Types

• Also called constants. • Integer literals can be of type int, uint, long or ulong depending on their value. Ex:12l or 12L is of long type

12ul or 12UL is of ulong type

12u of 12U is of unsigned integer type, uint

• Floating point literals of type doubleEx: 12.3F or 12.3f is of type float9.92M or 9.92m is of type decimal

• Boolean literalsEx:bool b = true;

Page 19: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 19

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

19

Types • Boxing

− Conversion of Value type to Reference Type− Allocates box, copies value into it

• Unboxing− Conversion of Reference Type back to Value Type− Checks type of box, copies value out

int int iValiVal = 123;= 123;object object oValoVal = = iValiVal;;int int iValueiValue = (= (int)oValint)oVal;;

123123iVal

oVal123123

System.Int32System.Int32

123123iValue

All types are derived from the object class, but the value types aren’t allocated on the heap. Value type variables actually contain their values. so how then can these types be stored in arrays and used in methods that expect reference variables ?Instead of writing wrapper code to convert from stack based memory to heap memory, you just need to assign a value type to an object and C# takes care of allocating the memory in the heap and generating a copy of that on the heap. When you attribute the object to a stack based int, the value is converted to the stack again. This process is what we call Boxing and Unboxing.“Boxing” refers to the process of implicit conversion of a value type to a reference type so that it can be manipulated like an object. Copies a value type into a reference type (object).A reference-type copy is made of the value type. Value type is converted implicitly to object, a reference type“Unboxing” is inverse operation of boxing. Copies the value out of the box. Copies from reference type to value type. Requires an explicit conversion. May not succeed (like all explicit conversions)Because of the allocation on the heap and copying the value type on to the heap it results in performance overhead

Page 20: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 20

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

20

Control Structures – if statement

• Requires a boolean expression

int iNum = 10;

if ((iNum % 2) == 0)

{

Console.WriteLine("Even Number");

}

else

{

Console.WriteLine("Odd Number");

}

Page 21: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 21

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

21

Control Structure – switch statement

• No two case constants in the same switch can have identical values.

• Fall through rule:− Statement sequence from one case cannot continue to next case. − Can be avoided by using the goto− Default statement cannot fall through− Empty cases can fall through.

Why C# does not allow fall through?(1) C# compiler allows the case statements to be re arranged for optimization(2) C# prevents a programmer from accidentally missing the break statement.

Page 22: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 22

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

22

Control Structure – switch statement

What is the output of the following code snippet?

int iNum=2;

switch(iNum)

{

case 1:

Console.WriteLine(iNum);

case 2:

Console.WriteLine(iNum);

break;

}

compile error - control cannot fall through from one

case to another

Page 23: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 23

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

23

Control Structure – switch statementchar cChoice='i';

switch(cChoice)

{

case 'a':

case 'e':

case 'i':

case 'o':

case 'u':

Console.WriteLine("Vowels");

break;

default:

Console.WriteLine("Consonants");

break;

}

Vowels

Page 24: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 24

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

24

Control Structures - loops

while loop:

while (condition)

{

statement/s ;

}

do-while loop:

do

{

statement/s;

}while(condition)

for loop:

for (initialization; condition; iteration)

{

statement/s;

}

break; continue;

Page 25: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 25

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

25

Types – User defined types

Delegate

Interface

Structure

Class

Arrays

Enumerations

Interfaces and Delegates are covered on day2.

Page 26: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 26

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

26

Enumerations

• Enumeration is a set of named integer constants.• General form of an enumeration:

enum name { enumeration list }

• The members of an enumeration are accessed through their type-name and the dot operator.

The statement:

Produces an output:green has a value : 1

enum eColors { red, green, blue};

Console.WriteLine (eColors.green + “ has a value : “ +

(int) eColors.green);

No two enum members can have the same name. Examples of enums:(1) Multiple enum members may share the same associated value. The exampleenum Color { Red, Green, Blue, Max = Blue } shows an enum in which two enummembers — Blue and Max — have the same associated value.(2) The exampleenum Circular { A = B, B } results in a compile-time error because the declarations of A and B are circular. A depends on B explicitly, and B depends on A implicitly.(3) Each enum member has an associated constant value. The type of this value is the underlying type for the containing enum. The constant value for each enummember must be in the range of the underlying type for the enum. The exampleenum Color: uint { Red = -1, Green = -2, Blue = -3 } results in a compile-time error because the constant values -1, -2, and –3 are not in the range of the underlying integral type uint.

Page 27: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 27

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

27

Enumerations

Consider:enum eColors { red, green=10, blue} ;

What are the values of the members?red 0

green 10

blue 11

Page 28: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 28

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

28

ArraysTwo ways of creating one dimensional array:

Two ways of initializing one dimensional array:

Two Dimensional array or rectangular array syntax:

int [] aiNum;

aiNum = new int[10]; int [] aiNum = new int[10];

int[] aiNum = {1,2,3};int [] aiNum;

aiNum = new int[] {1,2,3};

int[,] aiNum = new int[10,20];

Arrays allow a group of elements of a specific type to be stored in a contiguous block of memorySince arrays are of reference types, new operator must be used to allocate memory to arrays

Page 29: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 29

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

29

This slide has been intentionally left blank : Notes Page Contd.

Example on 1D array:using System;///<summary>///Class demonstrates array of integer values///</summary>class ArrayDemo{

///<summary>///Starting point of execution of the program///</summary>public static void Main(){

int[] arrofNum = new int[10];Console.WriteLine("Assign values to the array elements");for( int index=0; index < arrofNum.Length; index++){

arrofNum[index] = index;}Console.WriteLine("Displaying the array elemens");for( int index=0; index < arrofNum.Length; index++){Console.WriteLine(arrofNum[index]);

} } }

Page 30: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 30

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

30

Jagged Arrays

• Are two dimensional arrays in which the number of elements in each row can vary.

int[][] aiNum = new int[2][]; // array with 2 rows

aiNum[0] = new int[10]; // first row has 10 elements

aiNum[1] = new int[12]; // second row has 12 elements

Jagged Array

Page 31: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 31

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

31

Types : Reference Type - Class• Instantiated with new operator• It consists of members like

− Constants, fields, methods, operators, constructors, destructors− Properties, indexers, events

• Members can be− Instance members.− Static members.

class Employee

{

int iEmpId;

float fSalary;

void findSalary ()

{

// statements to calculate the salary

}

}

The syntax for defining classes in C# is simple

[attributes] [modifiers] class <classname> [:baseclassname]{[class – body]}[;]

A member of a class can be defined as static member or an instance member. By default, each member is defined as an instance member, which means that a copy of that member is made for every instance of the class. When you declare a member a static member, only one copy of the member exists. A static member is created when the application containing the class is loaded, and it exists throughout the life of an application. Therefore, you can access even before the class has been instantiated.

Page 32: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 32

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

32

Object

• Steps to instantiate a class Counter oCounterOne ;

oCounterOne = new Counter();

A reference oCounterOneto the Counter class is created .oCounterOne does not define Counter

The new operator dynamically allocates memory for an object of type Counter and returns a reference to it.

Note: The difference between a simple variable and the reference type variable is that, simple variable holds the valuewhere a reference type variable points to a value.

Object

Page 33: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 33

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

33

Objects in memory

• Objects can be created in one step.Ex: Counter oCounterOne = new Counter();

Points to

Object of type Counter

ReferenceVariable:

oCounterOne

Page 34: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 34

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

34

Object Reference Assignment

ocounterOne oCounterTwo

Statement: oCounterTwo = oCounterOne;

oCounterOne oCounterTwo

Consider: Counter oCounterOne, oCounterTwo;

Object Reference

Page 35: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 35

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

35

Access Modifiers

• Access modifiers specify who can use a type or a member• Access modifiers control encapsulation• Class members can be public, private, protected, internal, or

protected internal

to T or types derived from Tprotected

within T onlyprivate

to T or types derived from Tor to types within Aprotected internal

to types within Ainternal

to everyonepublic

Then a member defined in type T and Program A is accessible

If the access modifier is

The access modifiers with their description are as follows -public – Signifies that the member is accessible from outside the class’s definition and hierarchy of derived classes.protected – The member isn’t visible outside the class and can be accessed by derived classes only.private-The member can’t be accessed outside the scope of the defining class. Therefore, not even derived classes have access to these members.Internal- The member is visible only within the current compilation unit.Default access modifier for a member is private.

Page 36: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 36

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

36

Class - Fields

• A field − is a member variable of a class − holds data for a class .By default each object of a class has its own copy of every

field• Static fields are shared by multiple objects.

public float fSalary;

A field is a member variable used to hold a value. You can apply several modifiers to a field ,depending on how you want the field used .The modifiers include static, readonly and const. We’ll discuss what these modifiers signify and how to use them shortly.

Page 37: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 37

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

37

Class – Read only Fields

• Read only fields are constants• A read only field cannot be modified once initialized.• Are initialized in its declaration or in a constructor.

public class MyClass {public static readonly double dNum = Math.Sin(Math.PI);public readonly string sStrOne;public MyClass(string sStr) { sStrOne = sStr; } }

There will certainly be times when you have fields that you don’t want altered during execution of the application. To address these situations, C# allows for the definition of two closely related member types : constants and read-only fields.Constants ,represented by the const keyword – are fields that remain constant for the life of the application and their value is set at compile-time.When you define a field with the read-only keyword, you have the ability to set that field’s value in one place : constructor.

Page 38: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 38

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

38

Class – Methods

• All the executable code of a class is in its methods• Constructors, destructors and operators are special types of methods• Methods can have argument lists, statements, can return a value• By default, data is passed by value where a copy of the data is created and

passed to the method

Methods give classes their behavioral characteristics, and we name methods after the actions we want the classes to carry out on our behalf.A method is the actual code that acts on the object’s data (or field values).

Page 39: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 39

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

39

A complete class/// <summary>

/// This is a counter class to count

/// </summary>

class Counter {

//Counter variable

private int iCount;

/// <summary>

/// This method is used to increment the value of the count.

/// </summary>

public void increment() {

iCount++;

}

}

Class comment block

Method comment block

Page 40: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 40

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

40

Methods - ref parameters

ref modifier:• The ref modifier causes arguments to be passed by reference• The ref modifier has to be used in the method definition and the code that

calls it

Call statement:

void RefFunction(ref int iP)

{

iP++;

}

int iNum = 10;

RefFunction(ref iNum);

// iNum is now 11

ref keyword tells the C# complier that the arguments being passed point to the same memory as the variables in the calling code.That way,if the called method modifies the values and then returns, the calling code’s variables are modified.

Reference type variables are passed by reference to a method. but the reference of the object is passed by value. if you want the reference to be passed by reference, then use ref keyword along with the object.

Page 41: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 41

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

41

This slide has been intentionally left blank : Notes Page Contd.

Ex: using ref parameterusing System;

class RefSwap {int a, b;public RefSwap(int i, int j) {

a = i;b = j;

}public void show() {

Console.WriteLine(" a: {0}, b: {1}" ,a, b);}public void swap( ref RefSwap ob1, ref RefSwap ob2) {

RefSwap t;t = ob1;ob1 = ob2;ob2 = t;

}}

Page 42: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 42

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

42

This slide has been intentionally left blank : Notes Page Contd.

class RefSwapDemo {public static void Main() {

RefSwap x = new RefSwap(1,2);RefSwap y = new RefSwap(3,4);Console.Write("x before call");x.show();Console.Write("y before call");y.show();Console.WriteLine();x.swap( ref x, ref y);Console.Write("X after call");x.show();Console.Write("y after call");y.show();

}}

Page 43: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 43

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

43

Methods - out parameters

out modifier:• the out parameter is used in cases where you need to return a value from a

method, but not pass a value to the method. • use out parameter to return more than one value from the method.• out parameter will not have any initial values but must be assigned a value

before the method terminates.

Out Parameter

C# provides an alternate means of passing an argument whose changed value must be seen by the calling code : the out keyword. The significant difference between the ref keyword and the out keyword is that the out keyword doesn’t require the calling code to initialize the passes arguments first.

Page 44: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 44

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

44

Methods – passing variable number of arguments

• Methods can have a variable number of arguments, called a parameter array• params keyword declares parameter array• This must be last argument of the method and there can be only one such

argument.

int Sum(params int[] aiArr) {int iSum = 0;foreach (int iNum in aiArr)iSum += iNum;

return iSum;}

int iTotal = Sum(13,87,34);Parameter

The params parameter can be a variable number of parameters. params parameter allows us to gain the simplicity of treating all types as objects but pay a performance penalty when you need to treat those same parameters as specific types rather than generic objects.

Page 45: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 45

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

45

this keyword

• When a local variable of a method has the same name as that of the instance variable, the local variable hides the instance variable.

• In such cases, "this" can be used to refer to the instance variables.

class Demo

{

int i; // instance variable

public void fun (int i)

{

i = 10; // the local variable is referred

this.i = i; // to refer to the instance variable, this is used

}

}

Page 46: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 46

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

46

static

• use static to define a member that is independent of any objects• static members can not be accessed using an object of a class. instead, they

are accessed using the syntax: classname.staticmembername• when objects of a class containing static members are created, a copy of the

static members are not made• all the instances of the class share the same static variable

+Restrictions on static methods:

(a) this cannot be used in static methods

(b) static methods can call only static methods - because instance methods act on specific instances of the class but static methods do not.

(c) static methods can access static data directly.

A static member is a member that exists in a class as a whole ,rather than in a specific instance of the class. The key benefit of static method is that they reside apart from a particular instance of a class without polluting the application’s global space and without going against the object-oriented grain by not being associated with a class. If no initial values for a static variable are specified, then numeric values are initialized to zero and null for reference types.

Page 47: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 47

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

47

What is the output of the following code snippet?

using System;

class Test

{

public static void Main()

{

anotherMethod();

}

void anotherMethod()

{

Console.WriteLine(“Another Method”);

}

}

Compilation error: a non static method cannot be called from a static method

The correct form:using System;class Test{public static void Main(){Test t = new Test();t.anotherMethod();

}void anotherMethod(){Console.WriteLine(“Another Method”);

}}

Page 48: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 48

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

48

Method Overloading

• Two or more methods within the same class can have same name, but the parameters must vary.

• In general, the type or the number of parameters must differ.• The signature (name of the method and its parameter list) does not include a

params parameter if one is present. params does not participate in overloading

Method Overload

Method overloading enables the C# programmer to use the same method name multiple times with only the passes arguments changed.In C#, the signature includes the name of the method plus its parameter list. Note, it does not include the return type.

Page 49: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 49

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

49

Constructor

• Is special method that is called whenever an instance of the class is created.• It guarantees that the object will go through proper initialization before being

used.• It is without any return value.• It has same name as its class.• Access specifier must be public as constructors are called from outside the

class.• It can be overloaded.

Constructor

Constructors are special methods that are called when-ever an instance of the class is created. A key benefit of using a constructor is that it guarantees that the object will go through proper initialization before being used. When a user instantiates an object, that object’s constructor is called and must return before the user can perform any other work with that object. This guarantee helps ensure the integrity of the object and helps make applications written with object-oriented languages much more reliable.

If a class doesn’t define any constructors, an implicit parameter less constructor is createdIf a parameterized constructor is defined, then the default constructor is no longer used.

If no constructor is implemented then the default constructor is supplied.The default constructor initializes the data members with default values.If the constructors are implemented then no default constructor will be supplied

By overloading the constructor, you are giving flexibility to users the way in which objects can be created.Invoking an overloaded constructor using this: to invoke an overloaded constructor, you can use the this keyword.

Page 50: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 50

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

50

This slide has been intentionally left blank : Notes Page Contd.

using System;class Demo {

int x;int y;Demo(int i, int j)

{Console.WriteLine("invoking two arg constructor");x = i;y = j;

}Demo(int x) : this(x,x){Console.WriteLine("invoking the one arg constructor");

}Demo() : this(0,0)

{Console.WriteLine("invoking the default constructor");

}Demo( Demo d) : this(d.x, d.y) {{Console.WriteLine("invoking the one arg constructor - object");

}}

Page 51: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 51

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

51

This slide has been intentionally left blank : Notes Page Contd.

class Test{public static void Main(){

Demo d1 = new Demo();Demo d2 = new Demo(10);Demo d3 = new Demo(10,20);Demo d4 = new Demo(d2);

}}

Page 52: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 52

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

52

Static Constructors

• used to initialize the static variables• access modifiers like public are not allowed on static constructors• are called only once during the lifetime of the program

Static Constructor

A static constructor is handled in a special way : you can have only one static constructor ,it can’t take parameters, and it course can’t access instance members –including this pointer. A static constructor is executed before the first instance of a class is created. Access modifiers such a public and private aren’t allowed on static constructors.

Page 53: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 53

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

53

Destructors

• A destructor is a method that is called when an instance goes out of scope• Used to clean up any resources• Only classes can have destructors

~Employee()

{

// destruction code

}

C# destructors are not guaranteed to be called at a specific timeDestructor is called prior to garbage collection and not when the object goes out of scope.Ex: showing the destructorsusing System;class Demo {public static void Main(){

DestructorDemo d = new DestructorDemo(0);for (int i=0; i<100000; i++) {// create many objects that garbage collection must occurd.generateObject(i);

}}

}

Page 54: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 54

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

54

This slide has been intentionally left blank : Notes Page Contd.

class DestructorDemo {public int i;public DestructorDemo(int x){

i = x;}~DestructorDemo() {Console.WriteLine("Destructor called");

}// object is created here which goes out of scope immediatelypublic void generateObject(int s){

DestructorDemo d = new DestructorDemo(s);}

}

Page 55: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 55

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

55

Garbage Collection

• Automatic Memory Management Scheme

• Garbage Collector always run in background of an application.

An automatic garbage collector cleans up the heap memory on your behalf when it’s no longer needed. GC traces object references and identifies objects that can no longer be reached by running code. The GC doesn’t take up processor resources by running constantly, but it kicks periodically.A consequence of this last point is that heap memory garbage collection – and ,by extension ,object destruction – is nondeterministic. That is , under normal circumstances , you can’t be absolutely sure when the GC will run and therefore when your object will be finally destroyed .

You can force a garbage collection operation at any time with GC.Collect method.

Page 56: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 56

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

56

Finalize

• Finalize method is defined in Object class.

• A finalizer executes when the object is destroyed.

• In C# the declaration of the destructor is a short cut for the Finalize() method.

The Finalize method is called automatically after an object becomes inaccessible. The C# language doesn’t strictly support destructors. On the other hand, it does support overriding the Object.Finalize method. The only twist in the tale is that to override Finalize , you must write a method that’s syntactically identical to a destructor.

In C# the declaration of the destructor is a short cut for the Finalize() method.A finalizer executes when the object is destroyed. The finalizer is a protected method named FinalizeEx : protected void Finalize(){}

Page 57: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 57

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

57

Dispose

• Free resources that need to be reclaimed as quickly as possible.

• Explicitly called.

public void Dispose()

{

Console.WriteLine(“Dispose()”);

}

To achieve necessary explicit control and precise determinism in the destructor-like cleanup of unmanaged resources, you’re encouraged to implement an arbitrary Dispose method . The consumer of the object should call this method when the object is no longer required. This call can be made even if other references to the object are alive. Unlike, the finalizer , the Dispose method is arbitrary – in terms of its name, signature, access modifiers and attributes. You’re encouraged to use a public nonstatic method named Dispose ,with a void return and no parameters. This is only convention.

Page 58: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 58

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

58

Operators - overview

• C# provides a fixed set of operators, whose meaning is defined for the predefined types

• Some operators can be overloaded (e.g. +)• Associativity

− Assignment and ternary conditional operators are right-associative• Operations performed right to left• x = y = z evaluates as x = (y = z)

− All other binary operators are left-associative− Operations performed left to right− x + y + z evaluates as (x + y) + z− Use parentheses to control order

C# operator precedence is as follows - Primary, Unary, Multiplicative ,Additive ,Shift, Relational ,Equality ,Logical AND , Logical XOR , Logical OR ,Conditional AND ,Conditional OR ,Conditional and Assignment.

Page 59: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 59

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

59

class Car {string vid;public static bool operator ==(Car x, Car y) {

return x.vid == y.vid;}

}

Operator Overloading

• Operator Overloading helps in creating user-defined operations• The method used to overload the operator must be a static method

Operator overloading allows existing C# operators to be redefined so that one or both of the operator’s operands are of a user defined or struct type.

Restrictions on operator overloading(1) Precedence of the operators cannot be changed(2) Cannot alter the number of operands of the operator(3) You cannot overload any assignment operators such as += etc… - this cannot be

overloaded explicitly. But if += is used, automatically, the operator+ is called(4) You cannot overload the [] operator but indexers can be used for the same

purpose.

Page 60: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 60

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

60

Operator Overloading

--++falsetrue

~!-+

• Overloadable unary operators

• Overloadable binary operators

>=

!=

~

<=><>><<

==^|&%

!/*-+

Operator Overload

Overloading is not allowed for member access, method invocation, assignment operators, nor these operators: sizeof, new, &&, ||, and ?:.The && and || operators are automatically evaluated from & and |Overloading a binary operator (e.g. *) implicitly overloads the corresponding assignment operator (e.g. *=)

Page 61: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 61

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

61

Inheritance

• Using inheritance, you can create a general class that defines a common set of attributes and behaviors for a set of related items.

• A derived class is a specialized version of the base class and inherits all the fields, properties, operators and indexers defined by base class

• Protected members are private to the class but can be inherited and accessed by the derived class

The constructor of the base class can be called from the derived class using the keyword base.

Inheritance

Inheritance is used when a class is built upon another class, in terms of data or behaviour.To inherit one class from another, use the following syntaxclass <derivedclass>: <baseclass>

Private members of the base class will not be inherited to the derived class.

Page 62: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 62

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

62

Hidden Names and Inheritanceusing System;class Parent {

protected int p;public Parent(){

p = 10;}

}class Child : Parent {

int p;public Child() {

p = 100;}public void displayParent() {

Console.WriteLine(p);}

}

class InheritanceTest

{

public static void Main()

{

Child c = new Child();

c.displayParent();

}

}

What does the statement c.displayParent() display?

The child class member p hides the member p of the parent class.

To access the member p of the Parent class, use the syntax: base.member.

Refer to notes page for the above modified program

using System;///<summary>///Class representing the Parent///</summary>class Parent {

protected int p;///<summary>///Constructor of class Parent ///</summary>public Parent(){p = 10;

}}///<summary>///Class inheriting the class Parent///</summary>class Child : Parent{

int p;///<summary>///Constructor of Child class///</summary>public Child() {p = 100;

}

Page 63: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 63

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

63

This slide has been intentionally left blank : Notes Page Contd.

///<summary>///Method to display the Parent class’s member p

///</summary>public void displayParent() {Console.WriteLine(base.p);

}}

///<summary>///Class testing the Parent and Child classes///</summary>class InheritanceTest{

///<summary>///Starting point of execution of the program///</summary>public static void Main() {Child c = new Child();c.displayParent();

}}

Page 64: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 64

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

64

Base class reference can refer to a derived class object• A derived class object can be assigned to a base class reference• But the parent class reference cannot access the members of the derived class

Base Class Reference

Page 65: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 65

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

65

Method Overriding and Virtual Methods

• Method of a derived class can give another implementation to a method of the base class

• Method of the base class must be marked “virtual”• Method of the derived class must be marked “override”

class Employee //base class

{

protected double basic;

protected double gross;

public virtual void CalcSal()

{

gross = basic + 0.5*basic;

}

}

class Manager : Employee

{

protected double allow;

public override void CalcSal()

{

gross = basic + 0.5*basic + allow;

}

}

In inheritance, a derived class can give another implementation to a method of the base class. This is method overriding.to achieve overriding, the method of the base class must be marked as “virtual” and the method of the derived class must be marked as “override”Ex:class Employee{protected double basic;protected double gross;public virtual void CalcSal(){gross = basic + 0.5*basic;

}}

class Manager : Employee{protected double allowances;public override void CalculateSalary(){gross = basic + 0.5*basic + allowances;

}}

Page 66: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 66

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

66

This slide has been intentionally left blank : Notes Page Contd.

Note: If the method of base class is not marked “virtual”, even then it can be overridden in derived class by marking it new.Ex:class Employee{protected double basic;protected double gross;public void CalcSal(){gross = basic + 0.5*basic;

}}class Manager : Employee{protected double allowances;public new void CalculateSalary(){gross = basic + 0.5*basic + allowances;

}}

Page 67: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 67

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

67

Sealed modifier : methods

• Applied to methods:− Cannot be overridden

class class1{public override sealed int F1(){…….}}

class class2 : class1{public override int F1(){………}}

ERROR

Sealed methods:In C# methods can not be declared as sealed directlyBut a overriding method can be declared as sealed By doing so further overriding of the method can be avoided

Page 68: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 68

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

68

Sealed modifier : Class

• Applied to class− Cannot be derived

sealed class class1{} class class2 : class1

{

}

ERROR

Sealed class:A sealed class is one that cannot be used as a base classSealed classes can’t be abstractA class is sealed to prevent unintended derivation

Page 69: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 69

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

69

Abstract modifier

• Applied to methods:− Methods cannot have implementation in base class− Must be implemented in derived class and marked “override”− The class containing at least one abstract method must be declared

abstract

//base class

abstract class Employee

{

protected double basic;

protected double gross;

public abstract void CalcSal();

}

class Manager : Employee

{

protected double allow;

public override void CalcSal()

{

gross = basic + 0.5*basic + allow;

}

}

The abstract keyword can be used for method and class

An abstract method signifies it has no body (implementation), only declaration of

the method followed by a semicolon

public abstract double calculateArea();

If a class has one or more abstract methods declared inside it, the class must be

declared abstract

An abstract class cannot be instantiated ie objects cannot be created from an abstract

class

Reference of an abstract class can point to objects of its sub-classes thereby

achieving run-time polymorphism

Page 70: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 70

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

70

Abstract modifier - Demos

Abstract (class1.cs) Abstract (Class2.cs)

An abstract class is an incomplete class that cannot be instantiatedIntended to be used as a base classMay contain abstract and non-abstract function membersSimilar to an interfaceAbstract classes cannot be sealed

Page 71: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 71

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

71

Namespaces• Namespaces provide a way to uniquely identify a type.• Provides logical organization of types.• Namespaces can span assemblies.• Can be nested.• The fully qualified name of a type includes all namespaces.namespace N1 { // is referred to as N1

class C1 { // is referred to as N1.C1

class C2 { // is referred to as N1.C1.C2 }

}

namespace N2 { // is referred to as N1.N2 class C2 { // is referred to as N1.N2.C2

}

}

}

Fully Qualified name

Namespace

Namespaces are compilation units that let you organize and reuse code.There is no relationship between namespaces and file structure (unlike Java)

The using statement is used use types without typing the fully qualified namefully qualified name can also be usedEx: using N1;C1 a; // The N1. is implicitN1.C1 b; // Fully qualified nameC2 c; // Error! C2 is undefinedN1.N2.C2 d; // One of the C2 classesC1.C2 e; // The other oneThe using statement can also be used to create aliases using C = N1.N2.C1;using N = N1.N2;C a; // Refers to N1.N2.C1N.C1 b; // Refers to N1.N2.C1

Page 72: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 72

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

72

Predefined Types - Object

• Root of object hierarchy• Storage (book keeping) overhead

− 0 bytes for value types− 8 bytes for reference types

All data types inherit from the System.Object class in the .Net framework, which is aliased as object.

Page 73: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 73

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

73

Predefined Types - String

• A sequence of characters• Strings are immutable (once created the value does not change)• String is Reference type and string class in C# is an alias of System.String

class in the dot net framework• The following special syntax for string literals is allowed as they are built in

data types.− String s = “I am a string”;

System.StringString

System TypeC# Type

System.String class (or its alias , string) represents an immutable string ofcharacters. Methods like Replace(), Insert() etc. that appear to modify a string actually return a new string containing the modification.

Page 74: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 74

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

74

Predefined Types - StringBuilder

• Every time some modifications are done to the string a new String object needs to be created

• StringBuilder class can be used to modify string without creating a new string− Ex : StringBuilder str = new StringBuilder (“hi”);

• Properties:− Length

• Methods− Append()− Insert()− Remove()− Replace() StringBuilder str = new StringBuilder (“hi”);

str.Append(“how are you?”)

str.Insert(6,”How do you do?”);

String Builder

StringBuilder class is provided in System.Text namespace.

Page 75: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 75

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

75

Command Line Arguments

• Arguments can be passed to Main function at the command prompt from where the program is invoked.

• Main function can return an integer .• Four forms of Main:

− public static void Main()− public static int Main()− public static void Main(string[] args)− public static int Main(string[] args)

Command Line Arguments

The arguments specified at the command prompt will be put in an array of String type. In case we need to pass a numeric value at the command prompt, then we have to perform conversion from String to numeric type.Convert class can be used to convert from one base type to any other base type. In case of incompatible conversion, an exception is thrown.Following are few overloaded methods for conversion:Convert.ToDouble -> Converts a specified value to a double-precision floating point number. Convert.ToDecimal -> Converts a specified value to a Decimal number. Convert.ToInt64 -> Converts a specified value to a 64-bit unsigned integer.

Page 76: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 76

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

76

Structure

•Is a generalization of a user-defined data type (UDT)-Value type.

•Is created when you want a single variable to hold multiple types of related data.

•Is declared by using the keyword struct.

•Can also include methods as its members.

•member access levels possible are only public, internal, private

Structure

Like a class, a struct can contain other types and is sometimes referred to as a lightweight version of a class because internally it is a value type.The members of a structure are same as members in a class

Defining a struct takes an almost identical form to that of defining a class[attributes] [modifiers] struct <structname> [:interfaces]{

[struct–body]}[;]

Multiple interface inheritance is possible .Structures can implement one or more interfaces (Interfaces are discussed on Day 2)Members of the structure cannot be specified as abstract, virtual or protected

Page 77: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 77

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

77

This slide has been intentionally left blank : Notes Page Contd.

using System;struct Point{

public int x;public int y;public Point(int x,int y){

this.x=x;this.y=y;

}

public Point Add(Point pt){

Point newPt;newPt.x = x + pt.x;newPt.y = y+pt.y;return newPt;

}}

Page 78: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 78

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

78

This slide has been intentionally left blank : Notes Page Contd.

class StructExample{

static void Main(string [] args){

Point pt1 = new Point(1,1);Point pt2 = new Point(2,2);Point pt3;pt3= pt1.Add(pt2);Console.WriteLine("p3 : {0} : {1}",pt3.x,pt3.y);

}}

Page 79: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 79

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

79

Structure and Class - Similarities

• Both can have members, including constructors, properties, constants, and events.

•Both can implement interfaces.

•Both can have static constructors, with or without parameters.

Page 80: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 80

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

80

Structure and Class - Differences

A structure is a value type. A class is a reference type.

A structure can have instance constructors only if they take parameters.

A class can have instance constructors with or without parameters.

A structure is not inheritable. A class is inheritable from other existing classes.

StructureClass

Page 81: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 81

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

81

Summary

• Recap of OO• Basic Data Types and Control Structures • Structure• Classes and Objects • Garbage Collection• Static• Command Line Arguments• Inheritance• Overloading and Overriding• Abstract and Sealed• Namespaces• Structures

Page 82: C Sharp Programming SLIDES 01-FP2005-Ver1

ER/CORP/CRS/LA06/003 82

Copyright © 2005, Infosys Technologies Ltd

ER/CORP/CRS/LA30FC/003 Version no: 2.0

82

Thank You!


Recommended