131
1 1. Introduction 2. C# versus Java : highlights 3. C# data types 4. Defining custom data types 5. Operator Overloading 6. Event driven programming 7. .NET Framework Class Library 8. A GUI in C# 9. A web service in C#

Dr archana dhawan bajaj - c# dot net

Embed Size (px)

DESCRIPTION

Dr archana dhawan bajaj's Sales JetView.Dr archana dhawan bajaj is a renowned practising doctor of non-commercial of India and Dr archana various Hospitals and Meternity.Dr archana dhawan bajaj has a PH.d master's degree in both human & International client Management along with other fellow.Dr archana is known to be proficient in Hindi,English,Sanskrit and Urdu.Dr archana dhawan bajaj has acquired extensive practice experience in maternity primarily in relation to corporate and international matter delivery.Dr archana dhawan bajaj's Sales JetView.Dr archana dhawan bajaj is a renowned practising doctor of non-commercial of India and Dr archana various Hospitals and Meternity.Dr archana dhawan bajaj has a PH.d master's degree in both human & International client Management along with other fellow.Dr archana is known to be proficient in Hindi,English,Sanskrit and Urdu.Dr archana dhawan bajaj has acquired extensive practice experience in maternity primarily in relation to corporate and international matter delivery.Dr archana dhawan bajaj's Sales JetView.Dr archana dhawan bajaj is a renowned practising doctor of non-commercial of India and Dr archana various Hospitals and Meternity.Dr archana dhawan bajaj has a PH.d master's degree in both human & International client Management along with other fellow.Dr archana is known to be proficient in Hindi,English,Sanskrit and Urdu.Dr archana dhawan bajaj has acquired extensive practice experience in maternity primarily in relation to corporate and international matter delivery.Dr archana dhawan bajaj's Sales JetView.Dr archana dhawan bajaj is a renowned practising doctor of non-commercial of India and Dr archana various Hospitals and Meternity.Dr archana dhawan bajaj has a PH.d master's degree in both human & International client Management along with other fellow.Dr archana is known to be proficient in Hindi,English,Sanskrit and Urdu.Dr archana dhawan bajaj has acquired extensive practice experience in maternity primarily in relation to corporate and international matter delivery.Dr archana dhawan bajaj's Sales JetView.Dr archana dhawan bajaj is a renowned practising doctor of non-commercial of India and Dr archana various Hospitals and Meternity.Dr archana dhawan bajaj has a PH.d master's degree in both human & International client Management along with other fellow.Dr archana is known to be proficient in Hindi,English,Sanskrit and Urdu.Dr archana dhawan bajaj has acquired extensive practice experience in maternity primarily in relation to corporate and international matter delivery.Dr archana dhawan bajaj's Sales JetView.Dr archana dhawan bajaj is a renowned practising doctor of non-commercial of India and Dr archana various Hospitals and Meternity.Dr archana dhawan bajaj has a PH.d master's degree in both human & International client Management along with other fellow.Dr archana is known to be proficient in Hindi,English,Sanskrit and Urdu.Dr archana dhawan bajaj has acquired extensive practice exp

Citation preview

Page 1: Dr archana dhawan bajaj - c# dot net

1

1. Introduction 2. C# versus Java : highlights3. C# data types4. Defining custom data types5. Operator Overloading6. Event driven programming7. .NET Framework Class Library8. A GUI in C#9. A web service in C#

Page 2: Dr archana dhawan bajaj - c# dot net

2

C# and .NET

1. Introduction • History• C# features• .NET framework

2. C# versus Java : highlights3. C# data types4. Defining custom data types5. ...

Page 3: Dr archana dhawan bajaj - c# dot net

3

History

Builds on legacy from• C/C++ tradition -> new programming language C#• Java tradition : many ideas borrowed

• runtime environment : virtual machine• platform/language abstraction• guarded execution environment

• garbage collection• single rooted hierarchy• ...

Takes software development one step further towardscomponent based design

Page 4: Dr archana dhawan bajaj - c# dot net

4

Historyprocedural/structured design/programming

object oriented design/programming

component based design/programming

C/PASCAL

C++

JAVA

C#/.NET

component support possibleBUT NOT built into the language- templates- deployment descriptors

COM/COM+CORBA component model

Page 5: Dr archana dhawan bajaj - c# dot net

5

C# features : component orientedModern large-scale systems are component based

Properties

get/set

event based communication

support to annotate component for- deployment- configuration at design and/or runtime- component versioning- documentation

Page 6: Dr archana dhawan bajaj - c# dot net

6

C# features : OO paradigm

supports all typical OO mechanisms• encapsulation• inheritance• polymorphism• interface based programming

C++ legacy (NOT supported in Java)• support for operator overloading• user defined type conversions• rectangular arrays• pass-by-reference

Page 7: Dr archana dhawan bajaj - c# dot net

7

C# features : Excution model

NO own runtime library- uses .NET library (redesign of MS-library)

(implemented in C#)Compiles to intermediary language

(CIL - Common Intermediate Language)Executed by virtual machine

(CLR – Common Language Runtime)- memory management through garbage collection- guarded execution (e.g. array bounds guarding)- JIT compilation

Page 8: Dr archana dhawan bajaj - c# dot net

8

.NET framework

“.NET framework”

CLR

FCL Framework Class Library

Application Code

Version 1.0 released January 15, 2002

Page 9: Dr archana dhawan bajaj - c# dot net

9

.NET execution model

Platform AND language portabilityCLR can exploit processor/platform specific optimizationsSupported languages :

C#, J#, VB.NET, JScript, Microsoft IL, Managed Extensions for C++Supplied by 3rd parties :

COBOL, Eiffel, Haskell, Forth, Scheme, Smalltalk, Pascal, ...

CLR

CompilerApplication Code in “A Language”

CIL

Page 10: Dr archana dhawan bajaj - c# dot net

10

.NET : Common Type System

Cross language type system, allowing- type safety- cross language integration- execution services (garbage collection, JIT, exceptions, ...)

Defines rules to define types, irrespective of source languageAll types eventually mapped to CTS-types

e.g. cross language inheritanceJ# class inherits from C# class

Minimum subset for language to be supported by .NET :CLS – Common Language Specification- CLS-compliant language = “CLS consumer”- if more than CLS : “CLS extender”

C#= both CLS consumer and extender

Page 11: Dr archana dhawan bajaj - c# dot net

11

.NET : FCL categoriescomprises

- > 3500 classes- > 1 000 000 lines of code

• core functions• basic datatypes, collections• IO (network, console, file)• calls to runtime services

• database interaction• transactions• consuming/producing XML• manipulation of tables

• web-based applications (thin clients)

• desktop applications (thick clients)

• SOAP-based XML web services

Page 12: Dr archana dhawan bajaj - c# dot net

12

Hellonamespace Project1{ using System; class Class1 { static void Main() { Console.WriteLine("Hello there !"); for (int i = 0; i < 10; i++) Console.WriteLine(i); }}} package project1;

import java.lang.*;class Class1 {

public static void main(String[] args) { System.out.println("Hello there !"); for (int i = 0; i < 10; i++) System.out.println(i); }}

C#

Java

Page 13: Dr archana dhawan bajaj - c# dot net

13

C# and .NET

1. Introduction 2. C# versus Java : highlights3. C# data types4. Defining custom data types

Page 14: Dr archana dhawan bajaj - c# dot net

14

C# - Java : common approaches

Both intended as improvement to C++• Compilation to machine independent language, managed execution• Garbage Collection, no pointers

(C# allows pointer usage in special “unsafe” code sections)• Reflection API• No header files, no problems with circular (type) references• Single rooted hierarchy, objects allocated on the heap• Thread support by object-level lock• Multiple extension of interfaces, single inheritance for classes• Inner classes (closure instead of nested class)• Simple inheritance rules (no inheritance modifiers)• Everything is in a class (no global data, no global functions)• Arrays, strings : bounds checked at execution time• Systematic usage of “.” (instead of “->” and “::”)• Keywords for null pointer (null) and boolean type (boolean/bool)• Guaranteed initialization• if-statement controlled by boolean (instead of integer)• Finally-clause in try-catch blocks

Page 15: Dr archana dhawan bajaj - c# dot net

15

PropertiesC# : special support for getters/settersJava : implied by coding convention (template or “design pattern”)

Property int min Java style :

public int getMin() {return min;}public void setMin(int m) {min=m;}

C# style :public int Min {

get {return min;}set {min=value;}

}// value : implicit variable used when// calling setter method

- getter/setter grouped together- encourages to think in terms of properties

Page 16: Dr archana dhawan bajaj - c# dot net

16

IndexerMeans to index underlying datastructureJava style :

public class Bookshop {private Book[] books;// ...public void setBooks(int i,Book b) {

if(b!=null) books[i]=b;}public Book getBooks(int i) {return books[i];}

}C# style :

public class Bookshop {

private Book[] books;// ...public Book this[int i]{

get {return books[i];}set {if(value!=null) books[i]=value;}

} }// ...Bookshop standaard=new Bookshop();standaard[10]=new Book(“Harry Potter”);

Page 17: Dr archana dhawan bajaj - c# dot net

17

Event handling

Delegates used to handle events- Java equivalent : inner class object- C/C++ equivalent : function pointer

Direct support in C# for events

public delegate void TempChangeHandler(double t,ref bool cancel);public class Thermometer {

public event TempChangeHandler TempChange;double temp;public double Temperature{

get{return temp;}set{if(temp!=value) {

bool cancel=false;TempChange(value,ref cancel); // fire eventif(!cancel) temp=value;

}

}}

Page 18: Dr archana dhawan bajaj - c# dot net

18

Event handling

public class TempController {public TempController(Thermometer tm) {

tm.TempChange+=new TempChangeHandler(tm_TempChange);}private void tm_TempChange(double t,ref bool cancel) {

if(t>100) {cancel=true;System.Console.WriteLine(

"Way too hot : WRONG VALUE");} else {

System.Console.WriteLine("New temperature registered.");

}

}

}

Page 19: Dr archana dhawan bajaj - c# dot net

19

Event handling

public class Test {public static void Main() {

Thermometer term=new Thermometer();TempController tc=new TempController(term);term.Temperature=30;Console.WriteLine("Temp = {0}",term.Temperature);term.Temperature=120;Console.WriteLine("Temp = {0}",term.Temperature);

}}

Page 20: Dr archana dhawan bajaj - c# dot net

20

Enummerations

Standard Java approachpublic class Period {

public final static int DAILY=1;public final static int WEEKLY=2;public final static int MONTHLY=3;public final static int YEARLY=4;

}

// ...int publicationPeriod=Period.DAILY;// PROBLEM : does not prevent int publicationPeriod=12; ???

C# approachpublic enum Period{DAILY=1,WEEKLY=2,MONTHLY=3,YEARLY=4};Period publicationPeriod = Period.WEEKLY;

Page 21: Dr archana dhawan bajaj - c# dot net

21

Enummerations

Java 5 approachenum PeriodE{DAILY,WEEKLY,MONTHLY,YEARLY}//... int publicationPeriod=Period.DAILY;

System.out.println(publicationPeriod); PeriodE pubPeriod=PeriodE.DAILY; System.out.println(pubPeriod);

// OUTPUT : // 1 // DAILY

Page 22: Dr archana dhawan bajaj - c# dot net

22

Iterating over a CollectionStandard Java approach

for(Iterator i=collection.iterator();i.hasNext();) {Object o=i.next();// do something with o

}for(int i=0;i<array.length;i++) {

// do something with array[i]}

C# approachforeach(object o in collection) {

// do something with o}foreach(int i in array) {

// do something with i}

Java 5 approachfor(Object o : collection) {

// do something with o}for(int i : array) { // do something with i}

Page 23: Dr archana dhawan bajaj - c# dot net

23

Extension on “primitive” types

C# struct datatype :- very similar to class (defines attributes and methods)- BUT : - allocated on the stack or in-line (instead of heap)

- value type -> pass by value by default- efficient for small types- usage similar to usage of primitive types in Java

struct CoupleV{ private int x, y; public int X { set { x = value; } get { return x; } } public int Y { set { y = value; } get { return y; } } public string ToString() { return "(" + x + "," + y + ")"; }

Page 24: Dr archana dhawan bajaj - c# dot net

24

Extension on “primitive” types

public static void Main(){ CoupleV p = new CoupleV(); p.X = 10; p.Y = 20; CoupleV q=new CoupleV(); q.X = 20; q.Y = 30; Console.WriteLine(p.ToString()); Console.WriteLine(q.ToString()); CoupleV[] r = new CoupleV[4]; for (int i = 0; i < r.Length; i++) r[i].X = r[i].Y=i; foreach(CoupleV i in r) Console.WriteLine(i.ToString());}

Page 25: Dr archana dhawan bajaj - c# dot net

25

Operator OverloadingAllows to program type specific operator semanticsMore restrictive than C++ overloading mechanism

- always static- NON virtual (static binding !) !

public static bool operator ==(CoupleV a, CoupleV b) { return ((a.x == b.x) && (a.y == b.y)); } public static Boolean operator !=(CoupleV a, CoupleV b) { return !(a == b); }

// ...CoupleV p = new CoupleV();p.X = 10;p.Y = 20;CoupleV q = new CoupleV();q.X = 10;q.Y = 20;Console.WriteLine(p == q); // TRUEConsole.WriteLine((object)p == (object)q); // FALSE non-virtual !

Page 26: Dr archana dhawan bajaj - c# dot net

26

PolymorphismJava : all methods virtual (late binding) by defaultC# (like C++) : methods MUST be declared virtual if late binding applies

class A{ public virtual void f() {Console.WriteLine("A.f()");}}

class B : A{ public override void f() {Console.WriteLine("B.f()");}}

- shows intention of programmer- more efficient- can prevent later extensions ...- explicit interface implementation

(solving name conflicts in case of multiple interface implementation)- possibility to hide base class type/method in derived class

Page 27: Dr archana dhawan bajaj - c# dot net

27

AssembliesType boundaries

- class- namespace (equivalent to Java package)- assembly (equivalent to Java archive)

Assemby = exe/dll to deploy- meta-data (files contained, security settings, versioning info,

dependencies)- modules (compiled source files)- resources

Versioning- contained in assemby info- allows to run multiple versions of same types on same CLR

Page 28: Dr archana dhawan bajaj - c# dot net

28

Visibilityprivate

same as Java = default for interface and enum members

publicsame as Java =default for struct and class members

protected visible in type itself or derived types

internal visible in assembly= default for non-nested types

internal protectedvisible from type itself, in same assembly and in derived types (= private or protected or internal)

Type can not be more accessible then types used for its declaration

Page 29: Dr archana dhawan bajaj - c# dot net

29

Parameter modifiersPassing referencesref

pass reference to method requires parameter is assigned definite value before method entry

outrequires definite parameter assignment before returning frommethod call

Variable number of argumentsparams

can be applied to last argument of method

Parameter modifiers are part of method signature

Page 30: Dr archana dhawan bajaj - c# dot net

30

Parameter modifiers static void swap(ref int a, ref int b)

{ int t = a; a = b; b = t; } static void OneMore(int i, out int j) { j = i + 1; } static int sum(params int[] x) { int r = 0; foreach (int i in x) r += i; return r; }

// ...int x = 1, y = 2;

swap(ref x, ref y); Console.WriteLine("{0} - {1}",x, y); // 2 - 1 OneMore(x, out y); Console.WriteLine("{0} - {1}", x, y); // 2 - 3 Console.WriteLine(sum(1, 2, 3)); // 6 Console.WriteLine(sum(3, 4, 5, 6)); // 18

Page 31: Dr archana dhawan bajaj - c# dot net

31

AttributesAllow to extend language built-in declarative constructs

- Pre-defined attributes (e.g. Serialized)- Custom attributes

Can be applied to- class- method- field- parameter

Attributes and values can be retrieved at runtime

Page 32: Dr archana dhawan bajaj - c# dot net

32

Field modifiersconst

- value calculated at compile time- equivalent to Java final

readonly- value calculated at runtime- can only be assigned once !- allows to retrieve setting

(“a not so constant constant ...”)

Page 33: Dr archana dhawan bajaj - c# dot net

33

Pointer arithmetic

allowed in sections marked as unsafepointer type : <type>* dereferencing : *<pointer expression>address calculation : &<variable>

Garbage collector should NOT move around objectsused in unsafe regions

MUST be declared fixed

Page 34: Dr archana dhawan bajaj - c# dot net

34

Pointer arithmetic

unsafe static void AdditionOne(int[] b) { int l=b.Length; fixed (int* a = b) { int* p = a; for (int i = 0; i < l; i++,p++) *p = (*p) + 1; } }//...int[] k ={ 1, 2, 3, 4 };foreach (int a in k) Console.WriteLine("{0}", a); // 1 2 3 4AdditionOne(k);foreach (int a in k) Console.WriteLine("{0}", a); // 2 3 4 5

Page 35: Dr archana dhawan bajaj - c# dot net

35

Rectangular Arrays

int[,,] a=new int[3,4,5]; // rectangular array// single reference variable

a[1,2,3]=20;

int[][][] b=new int[3][4][5]; // jagged array

b[1][2][3]=30;

...

Page 36: Dr archana dhawan bajaj - c# dot net

36

Constructors - DestructorsVery similar to Java constructors – finalizersConstructor :

can contain explicit constructor callspecified outside constructor body

- call to other constructor of same type : this(...)- call to base class constructor : base(...)

DestructorNOT for value typeNO explicit calls to destructorC++-like syntax (actually expands to calling Finalize)

class A {

public A():this(1){}public A(int i):base(i){}~A() {/* Destructor */}

}

Page 37: Dr archana dhawan bajaj - c# dot net

37

C# and .NET

1. Introduction 2. C# versus Java : highlights3. C# data types4. Defining custom data types

Page 38: Dr archana dhawan bajaj - c# dot net

38

C# type systemValue types (struct, enum)Reference types (class, array, delegate, interface)Pointer type

struct CoupleV{ private int x, y; public CoupleV(int xx, int yy) { x = xx; y = yy; } public int X { set { x = value; } get { return x; } } public int Y { set { y = value; } get { return y; } } public override string ToString() { return "(" + x + "," + y + ")"; }}

Page 39: Dr archana dhawan bajaj - c# dot net

39

C# type system

class CoupleR{ private int x=0, y=0; public CoupleR(int xx, int yy) { x = xx; y = yy; } public int X { set { x = value; } get { return x; } } public int Y { set { y = value; } get { return y; } } public override string ToString() { return "(" + x + "," + y + ")"; }}

Page 40: Dr archana dhawan bajaj - c# dot net

40

C# type system

// ... CoupleR a = new CoupleR(1, 2); CoupleR b = a; CoupleV c = new CoupleV(3, 4); CoupleV d = c; a.X = 7; c.X = 7; Console.WriteLine(a); // (7,2) Console.WriteLine(b); // (7,2) Console.WriteLine(c); // (7,4) Console.WriteLine(d); // (3,4)

Page 41: Dr archana dhawan bajaj - c# dot net

41

Type unification

all struct and class types derive from object(pointer types do not ...)

“simple” (“primitive”) types are actually structsint : alias for System.Int32long : alias for System.Int64... boxing – unboxing- value type -> reference type : copy made (automatic)- reference type -> value type : explicit cast necessaryint x=12;object o=x; // box int y=(int)o; // unbox through downcast

Page 42: Dr archana dhawan bajaj - c# dot net

42

Available types

Value typessigned integer : sbyte, short, int, longunsigned integer : byte, ushort, uint, ulongfloating point : float, decimal, doublelogical : boolcharacters : char

Reference typesobjectstring

standard notations for constants apply (U : unsigned, L : long)standard rules for conversions apply

Page 43: Dr archana dhawan bajaj - c# dot net

43

Checked Arithmetic

checked(<expression>)checked {/* block */}

checks for integral overflowsgenerates runtime exception OverflowException

unchecked(<expression>)unchecked{/* block */}

turns off compile time bounds checking

Page 44: Dr archana dhawan bajaj - c# dot net

44

Control flow statementsSame as in Java, BUTswitch :

no “fall through” behavioureach case must end with jump (break, goto, ...)

foreach

goto label;

// ...int x=0;loop :

x++;if(x<5) goto loop;

Page 45: Dr archana dhawan bajaj - c# dot net

45

Namespaces

Similar to java packages w.r.t. avoiding name clashesBUT : no boundary for accessibilityCan be nestednamespace A {

namespace B {class CL {

}}

}

// ...A.B.CL x=new A.B.CL();

Alternative

using A.B;CL x=new CL();

Global namespace = default surrounding namespace

Page 46: Dr archana dhawan bajaj - c# dot net

46

C# and .NET

1. Introduction 2. C# versus Java : highlights3. C# data types4. Defining custom data types

Page 47: Dr archana dhawan bajaj - c# dot net

47

Classes[<attributes>][unsafe][<access modifier>][new][abstract | sealed] <class name>[: <base class> | : <interfaces> | : <base class>,<interfaces> ] {

<class members>}

Class members• Fields• Constants• Properties• Indexers• Methods• Events• Nested type (like Java static inner class, no outer object)

Page 48: Dr archana dhawan bajaj - c# dot net

48

ModifiersAccessibility (visibility) : private, internal, protected, publicInheritable

sealed : can not be overridden/inherited (Java equivalent : final)- sealed class- sealed method

abstract : MUST be overridden/inherited - abstract class- abstract method

class/method can not be sealed AND abstractParameter modifiers : ref,out,paramsClass member/instance member : staticLate binding/static binding : virtual, override, newDangerous ? : unsafe

- unsafe class- unsafe method- unsafe property

Page 49: Dr archana dhawan bajaj - c# dot net

49

Inheritanceclass A {}class B : A {}class C : B {}class D : A {}

Runtime type checking (RTTI)operator isif(a is A) {/* ... */}if(b is A) {/* ... */} // true if b is A or B

Conversions :- widening conversions (upcast) : automatic

B b = new B();C c = new C();D d = new D();A ab = b;A ac = c;B bc = c;B bd = d; // compile time errorA ad = d;

- narrowing (cntd.)

Page 50: Dr archana dhawan bajaj - c# dot net

50

Inheritance

- narrowing conversions : cast necessary- simple downcast :

B ba=(B)ab; // OKC ca=(C)ac; // OKD da=(D)ad; //OKD dc=(D)ac; // runtime error

- safe downcast (evaluates to null if unsuccesful)B ba = ab as B;C ca = ac as C;D dc = ac as D; // null

Page 51: Dr archana dhawan bajaj - c# dot net

51

PolymorphismKey idea : late binding, based on dynamic object typeC# : use virtual methods, override in derived class

class A{ public virtual void f() {Console.WriteLine("A.f()");}}class B : A{ public override void f() {Console.WriteLine("B.f()");}}class C : B { public override void f() { Console.WriteLine("C.f()"); }}class D : A{ public override void f() {Console.WriteLine("D.f()");}}

Page 52: Dr archana dhawan bajaj - c# dot net

52

Polymorphism

A a = new A();B b = new B();C c = new C();D d = new D();a.f(); // A.f()b.f(); // B.f()c.f(); // C.f()d.f(); // D.f()

A[] a = new A[] { new A(), new B(), new C(), new D() };foreach(A aa in a) aa.f();

// A.f()// B.f()// C.f()// D.f()

Page 53: Dr archana dhawan bajaj - c# dot net

53

PolymorphismSealingclass A{ public virtual void f() {Console.WriteLine("A.f()");}}class B : A{

public sealed override void f() {Console.WriteLine("B.f()");}}class C : B { public override void f() { Console.WriteLine("C.f()"); }}

NOT allowed

Page 54: Dr archana dhawan bajaj - c# dot net

54

PolymorphismHiding base class member : newclass A{public virtual void f() {Console.WriteLine("A.f()");}}class B : A{public override void f() {Console.WriteLine("B.f()");}}class C : B

{public new void f() { Console.WriteLine("C.f()"); }}class D : A{public override void f() {Console.WriteLine("D.f()");}}

A aa = new A(); aa.f(); // A.f() B bb = new B(); bb.f(); // B.f() C cc = new C(); cc.f(); // C.f() D dd = new D(); dd.f(); // D.f() A ab = new B(); ab.f(); // B.f()

A ac = new C(); ac.f(); // B.f() A ad = new D(); ad.f(); // D.f();

B bc = new C(); bc.f(); // B.f(); A[] a = new A[] { new A(), new B(), new C(), new D() };

foreach(A o in a) o.f(); // A.f() B.f() B.f() D.f()

Page 55: Dr archana dhawan bajaj - c# dot net

55

PolymorphismHiding base class member : newclass A{public virtual void f() {Console.WriteLine("A.f()");}}class B : A{public override void f() {Console.WriteLine("B.f()");}}class C : B

{public new void f() { Console.WriteLine("C.f()"); }}class D : A

{public new void f() {Console.WriteLine("D.f()");}} A aa = new A(); aa.f(); // A.f() B bb = new B(); bb.f(); // B.f() C cc = new C(); cc.f(); // C.f() D dd = new D(); dd.f(); // D.f() A ab = new B(); ab.f(); // B.f()

A ac = new C(); ac.f(); // B.f() A ad = new D(); ad.f(); // A.f(); B bc = new C(); bc.f(); // B.f(); A[] a = new A[] { new A(), new B(), new C(), new D() };

foreach(A o in a) o.f(); // A.f() B.f() B.f() A.f()

Page 56: Dr archana dhawan bajaj - c# dot net

56

Polymorphismnew

- define method as new (even if method with same signature, possibly sealed, exists in base class)- define new property- define new field

class A{protected double i; public double I {set{i = value;} get{return i;} } public sealed void f() {Console.WriteLine("A.f()");}}class B : A

{private new int i; public new int I {set{i = value;} get{return i;} } public new void f() {Console.WriteLine(“B.f()");}}

Page 57: Dr archana dhawan bajaj - c# dot net

57

Structs

Struct = class except for• value type, allocated on the stack• is implicitely sealed (inherit from single type, System.ValueType), can implement several interfaces• can NOT have destructor• NO field initializers (initialization to 0)• NO constructor that leaves fields uninitialized

struct CoupleV : A // not allowed unless A is interface{ private int x=1, y=1; // NOT allowed : field initializer public CoupleV(int xx) { x = xx; }

// NOT allowed : partial initialization public CoupleV(int xx, int yy) { x = xx; y = yy; } // allowed}

Page 58: Dr archana dhawan bajaj - c# dot net

58

Interfaces

Interface = class except for• no implementation, (pure abstract class)• can be supertype of struct (class can not !)

Interface members :- methods- properties- indexers- events

always : implicitly public, abstract, virtual and non static

Page 59: Dr archana dhawan bajaj - c# dot net

59

Interfacesinterface IP{void f();}interface IQ{void g();}

class A : IP{ public virtual void f() {Console.WriteLine("A.f()");}}class B : A,IQ { public override void f() {Console.WriteLine("B.f()");} public virtual void g() {Console.WriteLine("B.g()");}}class C : B { public override void f() { Console.WriteLine("C.f()"); } public override void g() { Console.WriteLine("C.g()"); }}class D : A{ public override void f(){Console.WriteLine("D.f()");}}class E : D,IQ { public override void f() { Console.WriteLine("E.f()"); } public virtual void g() { Console.WriteLine("E.g()"); }}

Page 60: Dr archana dhawan bajaj - c# dot net

60

InterfacesIP[] p = new IP[] { new A(), new B(), new C(), new D(), new E() };IQ[] q = new IQ[] { new B(), new C(), new E() };foreach (IP pp in p) pp.f();foreach (IQ qq in q) qq.g();

// A.f()// B.f()// C.f()// D.f()// E.f()// B.g()// C.g()// E.g()

Extending an interfaceinterface IPP : IP {

void ff();}

Page 61: Dr archana dhawan bajaj - c# dot net

61

Explicit interface implementationPROBLEM : implement two interfaces with name collision

-> explicit (instead of implicit) interface implementation interface U { void a(); } interface V { void a(); } class O : U, V { void U.a() { Console.WriteLine("A.ua()"); } void V.a() { Console.WriteLine("A.va()"); } }

// ... O o = new O();

// o.a(); // NOT allowed ((U)o).a(); // A.ua() ((V)o).a(); // A.va()

Page 62: Dr archana dhawan bajaj - c# dot net

62

Explicit interface implementation

LIMITATIONS (compared to implicit implementations)• NO late binding

no polymorphism related modifiers(no abstract, virtual, override, new)

• NO access modifierusage requires cast to interfaceaccess modifier mentioned there is used implicitely

Same rules (as with classes) to• convert between types• to convert to structs

Page 63: Dr archana dhawan bajaj - c# dot net

63

C# and .NET1. Introduction 2. C# versus Java : highlights3. C# data types4. Defining custom data types5. Operator Overloading6. Event driven programming7. .NET Framework Class Library8. A GUI in C#9. A web service in C#

Page 64: Dr archana dhawan bajaj - c# dot net

64

Operator overloadingIdea

• treat operators (+,-,*,/,%,...) as special functions(keyword operator)

• give special meaning to operator according to class semantics

• allows elegant programming for math-oriented software• important issue : what happens in case of mixed type expressions ?

-> need to overload also type conversion-> quite complex to keep consistent

-> not available in Java (but proposals are on the way ...)

Page 65: Dr archana dhawan bajaj - c# dot net

65

C# Operator overloadingOperators to overload

+ - ! ~ ++ -- (unary)

(binary)+ - * / % arithmetic& | ^ bit logic<< >> bit shift== != > < >= <= relational

CAN NOT BE OVERLOADED :- address related operators (unary *, &)- assignment ! (cf. C++ ...)

ONLY static operators allowedLOGIC pairs (MUST be overloaded together)

== and !=< and ><= and >=

Page 66: Dr archana dhawan bajaj - c# dot net

66

Indirect overloading

To keep things consistent (developer might forget to overload ...)

- && and || are evaluated using & and |- [] operator overloaded through indexers- combined assignment operators (+=, -=, *=, /=, ...) evaluated using non-combined counterparts

Page 67: Dr archana dhawan bajaj - c# dot net

67

Value equality

Operators == and != default to reference equalityIf other behavior is needed :

- override Equals method (cf. Java)- redirect Equals to “==“ and “!=“ -> allows compatibility with .NET languages

NOT supporting operator overloading -> allows polymorphism

Page 68: Dr archana dhawan bajaj - c# dot net

68

Value equality class Point { protected int x, y; public Point(int xx, int yy) { x = xx; y = yy; } public Point(int xx) : this(xx, xx) { } public Point() : this(0) { } public override string ToString() { return "<"+x+","+y+">"; } public static bool operator ==(Point a, Point b) { return (a.x == b.x) && (a.y == b.y); } public static bool operator !=(Point a, Point b) { return !(a == b); } }

Page 69: Dr archana dhawan bajaj - c# dot net

69

Value equalityProblem Collections framework heavily uses Equals()-method(implementation of no-duplicate collections such as Sets)

-> whenever == and != overloaded -> Equals() should be overridden

public override bool Equals(object o) { if (o is Point) { Point p = (Point)o; return this == p; } else return false; }

DO NOT call Equals() from within == and != ...

Page 70: Dr archana dhawan bajaj - c# dot net

70

Value equality : inheritance class Point3D : Point {

protected int z; public Point3D(int xx,int yy,int zz):base(xx,yy){z=zz;} public override string ToString() { return "<"+x+","+y+","+z+">"; } }// ...

Point a=new Point(1,1); Point b=new Point(2,2); Point c = new Point(2, 2); Point3D d=new Point3D(3,3,3); Point3D e = new Point3D(3, 3, 3); Point3D f = new Point3D(3, 3, 4); Console.WriteLine(a); // <1,1> Console.WriteLine(b); // <2,2> Console.WriteLine(e); // <3,3,3> Console.WriteLine(f); // <3,3,4>

Page 71: Dr archana dhawan bajaj - c# dot net

71

Value equality : inheritance Console.WriteLine(a == b); // False

Console.WriteLine(a == c); // False Console.WriteLine(a == d); // False Console.WriteLine(b == c); // True -> value ! Console.WriteLine(b == d); // False Console.WriteLine(c == d); // False Console.WriteLine(d == e); // True Console.WriteLine(e == f); // True

Operators == and != should be overloaded in Point3D public static bool operator ==(Point3D a, Point3D b)

{ return (a.x == b.x) && (a.y == b.y)&&(a.z==b.z); } public static bool operator !=(Point3D a, Point3D b) { return !(a == b); }// ...Console.WriteLine(e == f); // False

Page 72: Dr archana dhawan bajaj - c# dot net

72

Value equality : polymorphismPoint[] p ={ new Point(1, 1), new Point(2, 2),

new Point3D(1, 1, 1), new Point3D(2, 2, 2) };Point s1 = new Point(2, 2)Point s2 = new Point3D(2, 2, 2);foreach (Point pp in p) Console.WriteLine(pp == s1);foreach (Point pp in p) Console.WriteLine(pp == s2);

// False True False True// False True False True

CHANGE operator in base class (!)public static bool operator ==(Point a, Point b)

{ if(((a is Point3D)&&!(b is Point3D))||

(!(a is Point3D)&&(b is Point3D))) return false; else return (a.x == b.x) && (a.y == b.y); } public static bool operator !=(Point a, Point b) { return !(a == b); }

// False True False False// False False False True

Page 73: Dr archana dhawan bajaj - c# dot net

73

Overloading arithmetic operatorsOperator + Point p: translate over pOperator + int i: translate over Point(i,i)

public static Point operator +(Point a, Point b){ return new Point(a.x + b.x,a.y + b.y);}public static Point operator +(Point a,int i){ return new Point(a.x + i, a.y + i);}public static Point operator +(int i, Point a){ return a + i;}

//...Point a = new Point(10, 20);Point b = new Point(20, 30);Console.WriteLine(a + b); //<30,50>Console.WriteLine(a + 100); //<110,120>Console.WriteLine(100 + a + b); //<130,150>

Page 74: Dr archana dhawan bajaj - c# dot net

74

Type Conversion

Two versionsimplicit

not dangerous, can be invoked by compiler whenever neededexplicit

dangerous, only done if explicitely asked

e.g. conversion to and from intPoint-to-int : max value of x and y (looses info !)int-to-Point : Point on diagonal (no info lost !)

Page 75: Dr archana dhawan bajaj - c# dot net

75

Type Conversion public static Point operator +(Point a,int i) { Console.WriteLine("+(P,i)"); return new Point(a.x + i, a.y + i); } public static Point operator +(int i, Point a) { Console.WriteLine("+(i,P)"); return a + i; } public static implicit operator Point(int i) { Console.WriteLine("(P)i"); return new Point(i, i); } public static explicit operator int(Point p) { Console.WriteLine("(i)P"); return (p.x > p.y) ? p.x : p.y; }

Page 76: Dr archana dhawan bajaj - c# dot net

76

Type Conversion Point a = new Point(10,20);

Console.WriteLine((Point)5); // (P)i <5,5> Console.WriteLine(a + 5); // +(P,i) <15,25> Console.WriteLine((int)a + 5); //(i)P 25

In case NO +(Point,int) and +(int,Point) operators :

Console.WriteLine((Point)5); // (P)i <5,5> Console.WriteLine(a + 5); // (P)i <15,25> Console.WriteLine((int)a + 5); // (i)P 25

Page 77: Dr archana dhawan bajaj - c# dot net

77

C# and .NET

1. Introduction 2. C# versus Java : highlights3. C# data types4. Defining custom data types5. Operator Overloading6. Event driven programming

• delegates• events

7. .NET Framework Class Library8. A GUI in C#9. A web service in C

Page 78: Dr archana dhawan bajaj - c# dot net

78

Delegates[<attributes>][unsafe][<access modifiers>][new]delegate <return type> <delegate name> (<parameter list>);= type defining method signature- instance can hold (list of) method(s) with matching signature public delegate bool Filter(string s); class Del{ public static void Main(){ String[] r = new String[] { "a fair Lady",

"the king and I", "hye buzz", "a beautiful mind", "the zzz" };

Filter f=new Filter(StartWithA); ArrayList a=Show(r,f); Console.WriteLine("Starting with a :"); foreach (String s in a) Console.WriteLine(s); f=new Filter(EndWithZ); ArrayList z = Show(r, f); Console.WriteLine("Ending with z :"); foreach (String s in z) Console.WriteLine(s); } //... }

Page 79: Dr archana dhawan bajaj - c# dot net

79

Delegates class Del { // ... public static bool StartWithA(String s) { return s[0] == 'a'; } public static bool EndWithZ(String s) { return s[s.Length-1] == 'z'; } public static ArrayList Show(String[] s, Filter f) { ArrayList l = new ArrayList(); foreach(String i in s) if(f(i)) l.Add(i); return l; } }

Starting with a :a fair Ladya beautiful mindEnding with z :hye buzzthe zzz

Page 80: Dr archana dhawan bajaj - c# dot net

80

Multicast DelegatesUse operators += and -= to add/remove delegates to other delegateif non-void : return value of last invocation is returned

public delegate void M(int i); class Multi { // ... public static void Print(int i) { Console.WriteLine("i = {0}",i); } public static void Sqrt(int i) { Console.WriteLine(Math.Sqrt(i)); } public static void EndMessage(int i) { Console.WriteLine("Ending ..."); } }

Page 81: Dr archana dhawan bajaj - c# dot net

81

Multicast Delegates // public delegate void M(int i); class Multi { // ... public static void Main() { M m = null; Console.WriteLine("----------------------------"); m += new M(Print); m += new M(Sqrt); m += new M(EndMessage); m(12); Console.WriteLine("----------------------------"); m += new M(Print); m(16); Console.WriteLine("----------------------------"); m -= new M(Sqrt); m(25); Console.WriteLine("----------------------------"); m -= new M(Print); m(36); Console.WriteLine("----------------------------"); } }

-----------------i = 123,46410161513775Ending ...-----------------i = 164Ending ...i = 16-----------------i = 25Ending ...i = 25-----------------i = 36Ending ...-----------------

Page 82: Dr archana dhawan bajaj - c# dot net

82

Multicast DelegatesFrom within object -> invoked on this-object

public delegate void F(); public class A { public F f; private int i = 0; public A(int i) { this.i = i; f=null; f+=new F(Print); f+=new F(Inc); f+=new F(Print); f+=new F(Dec); f+=new F(Dec); f+=new F(Print); } public void Inc() { i++; } public void Dec() { i--; } public void Print() {Console.WriteLine(this);} public override string ToString(){return "<"+i+">";} public void IncAndDec() {f();}

Page 83: Dr archana dhawan bajaj - c# dot net

83

Multicast Delegates

From within object -> invoked on this-object// ...public static void Test() {

A a=new A(10); a.IncAndDec(); a.f(); } } class MultiObj { public static void Main() { A.Test(); A a = new A(20); a.f(); } }

<10><11><9><9><10><8><20><21><19>

Page 84: Dr archana dhawan bajaj - c# dot net

84

Delegate versus ...

Delegate vs. C function pointer- type safe (unless in unsafe regions ...)- can hold multiple methods to invoke- can hold instance to invoke method upon

Delegate vs. Interface- multiple methods to invoke

(could be implemented through list of interface objects)

- any problem solved with delegates can be solved using interface types- “more elegant”

Page 85: Dr archana dhawan bajaj - c# dot net

85

Delegate versus Inteface interface IF { bool Filter(string s); } class StartWithAFilter : IF { public bool Filter(string s) { return s[0] == 'a'; } } class EndWithZFilter : IF { public bool Filter(string s) { return s[s.Length - 1] == 'z'; } }

Page 86: Dr archana dhawan bajaj - c# dot net

86

Delegate versus Inteface class Test { public static void Main() { String[] r = new String[] { "a very fair Lady",

"the king and a z", "hye buzzy", "a beautiful mind for z", "the zzz" }; ArrayList a = Show(r, new StartWithAFilter()); Console.WriteLine("Starting with a :"); foreach (String s in a) Console.WriteLine(s); ArrayList z = Show(r, new EndWithZFilter()); Console.WriteLine("Ending with z :"); foreach (String s in z) Console.WriteLine(s); } public static ArrayList Show(String[] s, IF f) { ArrayList l = new ArrayList(); foreach (String i in s) if (f.Filter(i)) l.Add(i); return l; } }

Starting with a :a very fair Ladya beautiful mind for zEnding with z :the king and a za beautiful mind for zthe zzz

Page 87: Dr archana dhawan bajaj - c# dot net

87

Events

A

B

events- notification from A -> B- WITHOUT calling directly method on B

use of intermediary- event listeners + event handlers- in C# : implemented through delegates

event

Page 88: Dr archana dhawan bajaj - c# dot net

88

EventsA

B

event

Event Source

Event Sink

- delegate defined to fix handler signature- source class declares ability to fire event

-> public (downcast) multicast delegate d - delegates registered with d to get notified- source class fires event by calling delegate d

d

Delegate

delegate

delegate

delegate

Page 89: Dr archana dhawan bajaj - c# dot net

89

Events : ExampleCustomer arrives in business centre

-> generates event-> interested parties are notified

Delegate conventions for eventing - first argument : identifies source of event- second argument : additional info

subclass of EventArgs

Example- ID = object reference- additional info :

- time of event- urgency

Page 90: Dr archana dhawan bajaj - c# dot net

90

Events : ExampleDelegate signaturedelegate void CustomerHandler(object s, CustomerArgs e)

public delegate void CustomerHandler(object o,CustomerArgs e);enum Priority {LOW=0,NORMAL=1,HIGH=2};class CustomerArgs : EventArgs{ private DateTime d; public Priority p; public static Random r = new Random(); public DateTime Time { get { return d; } } public Priority Urgency { get {return p;} } public CustomerArgs() { d = DateTime.Now; p=(Priority)(r.Next(3)); }}

Preliminaries• Delegate declaration• Definition of event handler argument type

Page 91: Dr archana dhawan bajaj - c# dot net

91

Events : Example public class Customer { private string name; public event CustomerHandler CustomerArrival; public string Name { get { return name; } } public Customer(string n){name = n;} public void arrive() { if (CustomerArrival != null) { CustomerArgs args = new CustomerArgs(); CustomerArrival(this, args); // fire the event; } } public override string ToString(){return "<Customer : "+name+">";} }

Event source class : Customer• Declares event • Listeners will register to event• FIRES event when needed

Page 92: Dr archana dhawan bajaj - c# dot net

92

Events : Example class HotelService {private string n; public HotelService(string n) {this.n=n;} public string Name{get{return n;}} public void CustomerArrivalNotification(object o,CustomerArgs a) { Console.WriteLine(this + " : guest " + (Customer)o + " arrived at " + (a.Time)+"(Priority : "+a.Urgency+")"); } public override string ToString() { return "Hotel service : "+n; } } class HotelPersonnel {private string n; public HotelPersonnel(string n) {this.n=n;} public string Name{get{return n;}} public void CustomerArrivalNotification(object o,CustomerArgs a) { Console.WriteLine(this + " : guest " + (Customer)o + " arrived at" + (a.Time) + "(Priority : " + a.Urgency + ")"); } public override string ToString() { return "Hotel personnel : "+n; } }

Event sink classes :• HotelService• HotelPersonnel• declare a method conforming to delegate signature

Page 93: Dr archana dhawan bajaj - c# dot net

93

Events : Example class CustomerApp { public static void Main() { Customer[] c=new Customer[] {new Customer("Bart De Poorter"), new Customer("George Bush"), new Customer("Condaleeza Rice"), new Customer("Mahatma Ghandi")}; HotelService[] hs = new HotelService[] { new HotelService("House keeping"), new HotelService("Accounting"), new HotelService("Reception") }; HotelPersonnel[] hp = new HotelPersonnel[] { new HotelPersonnel("Manager"), new HotelPersonnel("Mr. BigBoss (owner)") }; foreach(HotelService h in hs) { foreach(Customer cu in c) cu.CustomerArrival+= new CustomerHandler(h.CustomerArrivalNotification); }

// ...

Main method• instantiates simulation objects• binds sinks to sources

Page 94: Dr archana dhawan bajaj - c# dot net

94

Events : Example// ...

foreach (HotelPersonnel h in hp) { c[1].CustomerArrival +=

new CustomerHandler(h.CustomerArrivalNotification); c[2].CustomerArrival +=

new CustomerHandler(h.CustomerArrivalNotification); } Console.WriteLine("Starting simulation ----------------"); foreach (Customer cc in c) { cc.arrive(); try { System.Threading.Thread.Sleep(1000); } catch (System.Threading.ThreadInterruptedException e) { } Console.WriteLine("---------------------"); } } }

Page 95: Dr archana dhawan bajaj - c# dot net

95

Events : Example

Starting simulation ----------------Hotel service : House keeping : guest <Customer : Bart De Poorter> arrived at 14/12/2005 9:57:06(Priority : NORMAL)Hotel service : Accounting : guest <Customer : Bart De Poorter> arrived at 14/12/2005 9:57:06(Priority : NORMAL)Hotel service : Reception : guest <Customer : Bart De Poorter> arrived at 14/12/2005 9:57:06(Priority : NORMAL)---------------------Hotel service : House keeping : guest <Customer : George Bush> arrived at 14/12/2005 9:57:07(Priority : LOW)Hotel service : Accounting : guest <Customer : George Bush> arrived at 14/12/2005 9:57:07(Priority : LOW)Hotel service : Reception : guest <Customer : George Bush> arrived at 14/12/2005 9:57:07(Priority : LOW)Hotel personnel : Manager : guest <Customer : George Bush> arrived at14/12/2005 9:57:07(Priority : LOW)Hotel personnel : Mr. BigBoss (owner) : guest <Customer : George Bush> arrived at 14/12/2005 9:57:07(Priority : LOW)---------------------Hotel service : House keeping : guest <Customer : Condaleeza Rice> arrived at 14/12/2005 9:57:08(Priority : NORMAL)Hotel service : Accounting : guest <Customer : Condaleeza Rice> arrived at 14/12/2005 9:57:08(Priority : NORMAL)Hotel service : Reception : guest <Customer : Condaleeza Rice> arrived at 14/12/2005 9:57:08(Priority : NORMAL)Hotel personnel : Manager : guest <Customer : Condaleeza Rice> arrived at14/12/2005 9:57:08(Priority : NORMAL)Hotel personnel : Mr. BigBoss (owner) : guest <Customer : Condaleeza Rice> arrived at14/12/2005 9:57:08(Priority : NORMAL)---------------------Hotel service : House keeping : guest <Customer : Mahatma Ghandi> arrived at 14/12/2005 9:57:09(Priority : HIGH)Hotel service : Accounting : guest <Customer : Mahatma Ghandi> arrived at 14/12/2005 9:57:09(Priority : HIGH)Hotel service : Reception : guest <Customer : Mahatma Ghandi> arrived at 14/12/2005 9:57:09(Priority : HIGH)---------------------

Page 96: Dr archana dhawan bajaj - c# dot net

96

C# and .NET

1. Introduction 2. C# versus Java : highlights3. C# data types4. Defining custom data types5. Operator Overloading6. Event driven programming7. .NET Framework Class Library8. A GUI in C#9. A web service in C#

Page 97: Dr archana dhawan bajaj - c# dot net

97

FCL-CLS compliant set of managed type- accessible from all .NET languages- grouping (3542 types) :

- logically in namespaces (120)- deployed as a set of assemblies (36) of .NET framework

System

- collection of core classes (Object, ValueType, Enum, Convert, Exception)- core interfaces (ICloneable, IComparable, ...)- time related classes (DateTime, TimeSpan)- support for

- delegates- mathematical operations- custom attributes (Attribute)- exception handling- strings (String)

Page 98: Dr archana dhawan bajaj - c# dot net

98

FCLSystem.Text

- immutable string (System.String)- mutable string (StringBuilder)- regular expressions (System.Text.RegularExpressions)

C# string is alias for System.Stringoverloaded “==“ operator for equality check (NOT in Java !)indexing strings : use normal indexing mechanism ([])

string a=“abcde”;char c=a[2];

formatting strings (Format()-method)format specifier string :

{ParamIndex[,MinWidth][:FormatString]}

e.g. “Value of account {0} is {1:C}” (C -> “Currency”)

Page 99: Dr archana dhawan bajaj - c# dot net

99

FCLSystem.Collections

- Java-like set of interfaces and classes, implementing popular data structures (ArrayList, Queue, Stack, BitArray, ...)- System.Array is base type for all array types- generics as of .NET v 2.0 (System.Collections.Generics)to iterate over Collection :

- Collection implements IEnumerablepublic interface IEnumerable {

IEnumerator GetEnumerator();}

- iterator implements IEnumeratorpublic interface IEnumerator {

bool MoveNext();object Current {get;}void Reset();

}

- also : foreach idiom can be used

Page 100: Dr archana dhawan bajaj - c# dot net

100

FCLiterator for Dictionary (Java Map)

public interface IDectionaryEnumerator : IEnumerator {DictionaryEntry Entry {get;}object Key {get;}object Value {get;}

}

IEnumerable

ICollection

IList

IDictionary

get iterator

support for countingconverting to array

indexed collection

Page 101: Dr archana dhawan bajaj - c# dot net

101

FCLclass Array : ICollection, IEnumerable, IList

fixed size indexed arrayclass ArrayList : IList

dynamically sized arrayclass Hashtable : IDictionary

standard dictionary key/value pairshash computed using GetHashCode() method

-> should be overridden class Queue

FIFO data structuremethods to queue and dequeue

class StackLIFO data structurekey methods : push and pop

Page 102: Dr archana dhawan bajaj - c# dot net

102

FCL

class Bitarraycompressed form of bool[] (one bit per boolean)

class SortedList : IDictionarysorted to increase lookup efficiency(binary search instead of linear search)

class StringCollection : ICollectionspecial purpose collection for storing strings

class StringDictionary : IEnumerableidem for storing string maps

Page 103: Dr archana dhawan bajaj - c# dot net

103

FCL : Examplespublic static void Print(ICollection c){ int j = 0; foreach(object i in c) Console.WriteLine("{0} -> {1}",j++,i); Console.WriteLine("--------------------"); }

ArrayList al = new ArrayList(); al.Add("Wim"); al.Add("Ann"); al.Add("Bram"); al.Add("Bart"); al.Add("Greet"); Print(al); al.Sort(); Print(al); Console.WriteLine(al[1]); al[1] = "BART"; Print(al);

0 -> Wim1 -> Ann2 -> Bram3 -> Bart4 -> Greet--------------------0 -> Ann1 -> Bart2 -> Bram3 -> Greet4 -> Wim--------------------Bart0 -> Ann1 -> BART2 -> Bram3 -> Greet4 -> Wim--------------------

Page 104: Dr archana dhawan bajaj - c# dot net

104

FCL : ExamplesHashtable h = new Hashtable();h["Wim"] = "onetwothree";h["Bram"] = "123";h["Greet"] = "Da Vinci";h["Ann"] = "My fair lady";Console.WriteLine(h["Bram"]); // 123

Queue q = new Queue();Stack s = new Stack();int[] a ={ 1, 2, 3, 4 };foreach (int i in a) {q.Enqueue(i); s.Push(i);}Print(q);Print(s);Console.WriteLine(q.Dequeue());Console.WriteLine(s.Pop());Print(q);Print(s);

1230 -> 11 -> 22 -> 33 -> 4--------------------0 -> 41 -> 32 -> 23 -> 1--------------------140 -> 21 -> 32 -> 4--------------------0 -> 31 -> 22 -> 1--------------------

Page 105: Dr archana dhawan bajaj - c# dot net

105

FCL : SortingTwo options :

- object ordering implemented in the class itselfpublic interface IComparable {

int CompareTo(object o);}

- delegate ordering to special objectpublic interface IComparer {

int Compare(object o1,object o2);}

comparing must follow special contract1. if a comes before b -> a.CompareTo(b)<02. if a is equal to b -> a.CompareTo(b) == 03. if a comes after b -> a.CompareTo(b)>04. null first -> a.CompareTo(null)>05. a.CompareTo(b) -> a.GetType() == b.GetType()

Page 106: Dr archana dhawan bajaj - c# dot net

106

FCLSystem.IO

- standard in, out and error stream- binary and text file I/O- registering/notification of filesystem events- access of user specific secure storage (“Isolated Storage”)- System.Console- System.IO.IsolatedStorage

System.Net

- classes for network communication- raw socket access, TCP, UDP sockets- HTTP support- System.Net- System.Net.Sockets- System.IO.Stream

Page 107: Dr archana dhawan bajaj - c# dot net

107

FCL

System.Security

- security policies, principals, permission sets, evidence (authentication, key, ...)- cryptographic library

System.Threading

- support for thread management and pool management- synchronization mechanisms

- locks (monitor): serialized access- pulse/wait : notify waiting threads

- System.Timers- System.Thread

Page 108: Dr archana dhawan bajaj - c# dot net

108

FCL

System.Reflection

- retrieve type information (methods, class names, signatures, ...) at runtime- retrieve (custom) attributes at runtime

-> for each custom attribute : - CLR creates object- retrieved using reflection interface

- retrieve metadata at runtime- assembly info (version, target OS, ...)- data to create custom attributes stored as metadata

Page 109: Dr archana dhawan bajaj - c# dot net

109

FCLSystem.Runtime.Serialization

- write object graph to/from stream (file or network)- default serializers : XML and binary- serializability : use non-custom attribute [Serializable]- System.SerializableAttribute- System.NonSerializableAttribute

System.Runtime.Remoting

- distributed object model of .NET- calls can be : synchronous, asynchronous, one-way- transport protocol : TCP, HTTP or SMTP- format : binary or SOAP- naming service, activation service, marshalling, messaging

Page 110: Dr archana dhawan bajaj - c# dot net

110

FCL

System.Web.Services

- in fact part of ASP.NET (not part of CLR)- describe, discover and publish web services

System.Data

- known as ADO.NET- classes to support database access

System.Xml

- schemas, namespaces, parsing (DOM,SAX)- implementation of XSLT, XPath, SOAP1.1

Page 111: Dr archana dhawan bajaj - c# dot net

111

FCLSystem.Drawing

- support for graphics - known as GDI+- brushes, fonts, bitmaps, rendering, drawing primitives, ...

System.Windows.Forms

- Rich client applications (“classic GUIs”)- known as “Windows Forms”- forms package, GUI components and RAD component model

System.Web

- Thin client applications - known as “Web Forms”- server side package creates HTML UI- support for session management (state), security, deployment, ... - part of ASP.NET

Page 112: Dr archana dhawan bajaj - c# dot net

112

FCL

System.Globalization

- date/time conversions- string adaptation to locale- resource file to centralize locale data

System.Configuration

- per user, per application configuration management

System.EnterpriseServices

- advanced services- distributed transaction, object pooling, queuing, event handling- reliable asynchronous messaging- access to directory service

Page 113: Dr archana dhawan bajaj - c# dot net

113

C# and .NET

1. Introduction 2. C# versus Java : highlights3. C# data types4. Defining custom data types5. Operator Overloading6. Event driven programming7. .NET Framework Class Library8. A GUI in C#9. A web service in C#

Page 114: Dr archana dhawan bajaj - c# dot net

114

GUIs in .NET

- heavily uses delegates- event subscription- event notification

- Visual Studio .NET contains IDE to assist GUI development- choose New Project -> “Windows Application”

(instead of “Console Application”)- Add WinForms as needed- Drop components from ToolBox on each form- Change component state in IDE generated code- Code event handlers

Page 115: Dr archana dhawan bajaj - c# dot net

115

Example : incrementor

System.Windows.Forms.Buttondeclares properties : Name, Textfires events :

System.EventHandler Click

System.Windows.Forms.TextBox declares properties : Name, Text

System.Windows.Forms.Formdeclares properties :

Name, Text Controls (container)

fires events :System.EventHandler Load

Page 116: Dr archana dhawan bajaj - c# dot net

116

Example : incrementorMain()-methodusing System;using System.Collections.Generic;using System.Windows.Forms;

namespace WindowsApplication1{ static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } }}

IDE-generated[Program.cs]

Page 117: Dr archana dhawan bajaj - c# dot net

117

Example : incrementorForm1-classnamespace WindowsApplication1{

partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null;

/// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources

/// should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); }

IDE-generated(edited)[Form1.Designer.cs]

Page 118: Dr archana dhawan bajaj - c# dot net

118

Example : incrementor#region Windows Form Designer generated code/// <summary>/// Required method for Designer support - do not modify/// the contents of this method with the code editor./// </summary>private void InitializeComponent(){

this.button1 = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // button1 // this.button1.Location = new System.Drawing.Point(92, 150); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 0;

this.button1.Text = "Click here"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click);

IDE-generated(edited)[Form1.Designer.cs]

Form1-class

Page 119: Dr archana dhawan bajaj - c# dot net

119

Example : incrementorForm1-class

// // textBox1 // this.textBox1.Location = new System.Drawing.Point(78, 103); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(100, 20); this.textBox1.TabIndex = 1; this.textBox1.TextChanged +=

new System.EventHandler(this.textBox1_TextChanged);

IDE-generated(edited)[Form1.Designer.cs]

Page 120: Dr archana dhawan bajaj - c# dot net

120

Example : incrementor // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(292, 266); this.Controls.Add(this.textBox1); this.Controls.Add(this.button1); this.Name = "Form1";

this.Text = "Incrementer"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); this.PerformLayout(); }

#endregion

private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox textBox1; }}

IDE-generated(edited)[Form1.Designer.cs]

Form1-class

Page 121: Dr archana dhawan bajaj - c# dot net

121

Example : incrementornamespace WindowsApplication1

{ public partial class Form1 : Form { int i = 0; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e){} private void button1_Click(object sender, EventArgs e) {

i++; textBox1.Text = ""+i; } private void textBox1_TextChanged(object sender, EventArgs e) { } }}

template IDE-generatedhandler code to add ![Form1.cs]

Form1-class

Page 122: Dr archana dhawan bajaj - c# dot net

122

C# and .NET

1. Introduction 2. C# versus Java : highlights3. C# data types4. Defining custom data types5. Operator Overloading6. Event driven programming7. .NET Framework Class Library8. A GUI in C#9. A web service in C#

Page 123: Dr archana dhawan bajaj - c# dot net

123

.NET / C# web service

- actually part of ASP.NET- uses .asmx file to bind server to code- C# :

- web service derives from System.Web.Services.WebService- class must be public, must have public constructor- has [WebService] attribute

paramters :- Description : info- Name : default = class name- Namespace : XML-namespace

- every exposed service method should have attribute[WebMethod]

parameters include :-Description : info-EnableSession : default = false- MessageName : default = method name

Page 124: Dr archana dhawan bajaj - c# dot net

124

.NET / C# web service

web server- runs .asmx -file - locates class files referred- loads, runs and manages code

client- statically retrieves WSDL document- generates and compiles proxy class- instantiates service proxy- call methods on the proxy

Page 125: Dr archana dhawan bajaj - c# dot net

125

Hello Service

Server side

Create ASP.NET Web Service projectFile -> New -> Web SiteASP.NET Web Service template

Edit [WebService] attribute (if necessary)Add class logic, give any WS method [WebMethod] attributeBuild projectRun ProjectCheck if service is running (WSDL-file)

http://localhost:1665/WebSite1/?.asmx ? WSDLInvoke method from browser to check proper functioning

Page 126: Dr archana dhawan bajaj - c# dot net

126

Hello Service

Service.asmx

<%@ WebService Language="C#" CodeBehind="~/App_Code/Service.cs" Class="Service" %>

Page 127: Dr archana dhawan bajaj - c# dot net

127

Hello ServiceService.csusing System;using System.Web;using System.Web.Services;using System.Web.Services.Protocols;

[WebService(Namespace = "http://tempuri.org/")][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]public class Service : System.Web.Services.WebService{ public Service () {

//Uncomment the following line if using designed components //InitializeComponent(); }

[WebMethod] public string HelloWorld(string e) { return "Hello World there, "+e; } }

Page 128: Dr archana dhawan bajaj - c# dot net

128

Hello ServiceWSDL (http://localhost:1655/WebSite1/Service.asmx?WSDL)

Page 129: Dr archana dhawan bajaj - c# dot net

129

Hello ServiceService invocation from browser

(http://localhost:1655/WebSite1/Service.asmx?op=HelloWorld)

Answer :<string>Hello World there, MyName</string>

Page 130: Dr archana dhawan bajaj - c# dot net

130

Hello ServiceClient side

Create Windows Console project (or GUI project ...)Open WS project and add to current solutionAdd Web Reference

-> Browse local host-> Select Web Reference (= namespace for proxy)

(Here : HelloService)Add client code

-> instantiate proxy object-> call WS methods on proxy

Page 131: Dr archana dhawan bajaj - c# dot net

131

Hello Serviceusing System;using System.Collections.Generic;using System.Text;

namespace ConsoleApplication3{ class Program { static void Main(string[] args) { HelloService.Service s = new HelloService.Service(); Console.WriteLine(" -> " + s.HelloWorld("Georgie ")); } }}

-> Hello World there, GeorgiePress any key to continue . . .