oops.ppt

65
Object Oriented Concepts – Object Oriented Concepts – C# C# Nauzad Kapadia Nauzad Kapadia Q Q

Upload: kiran-moy-mandal

Post on 03-Jan-2016

16 views

Category:

Documents


0 download

DESCRIPTION

OBJECT ORIENTED PROGRAMMING

TRANSCRIPT

Page 1: OOPs.ppt

Object Oriented Concepts – Object Oriented Concepts – C#C#

Nauzad KapadiaNauzad Kapadia

QQ

Page 2: OOPs.ppt

InterfacesInterfaces

An interface defines a contractAn interface defines a contractAn interface is a typeAn interface is a type

Can declare variables of that typeCan declare variables of that typeHowever, you cannot directly instantiate an interfaceHowever, you cannot directly instantiate an interface

Includes methods, properties, indexers, eventsIncludes methods, properties, indexers, events

Any class or struct implementing an interface must support all parts of Any class or struct implementing an interface must support all parts of the contractthe contract

Interfaces provide no implementationInterfaces provide no implementationWhen a class or struct implements an interface it must provide the When a class or struct implements an interface it must provide the implementations for all members of the interfaceimplementations for all members of the interface

Interfaces provide polymorphismInterfaces provide polymorphismMany classes and structs may implement a particular interfaceMany classes and structs may implement a particular interface

Page 3: OOPs.ppt

public interface IDisposable { void Dispose();}public class TextBox : IDisposable { public void Dispose() { ... }}public class Car : IDisposable { public void Dispose() { ... }}

InterfacesInterfacesExampleExample

void PolyDispose(IDisposable id) { id.Dispose();} TextBox tb = new TextBox();

PolyDispose(tb);

Car c = new Car();PolyDispose(c);

Page 4: OOPs.ppt

InterfacesInterfacesCastingCasting

A class that implements an interface can be cast A class that implements an interface can be cast (converted) to any of those interfaces(converted) to any of those interfaces

public interface IDisposable {}public interface IEnumerable {}public class ListBox : IDisposable, IEnumerable {}

ListBox lb = new ListBox();IDisposable id = (IDisposable)lb;IEnumerable ie = (IEnumerable)lb;

Page 5: OOPs.ppt

interface ITextBox { void SetText(string s);

}

interface IListBox { void SetItems(string[] items);}

interface IComboBox: ITextBox, IListBox {

}

InterfacesInterfacesMultiple InheritanceMultiple Inheritance

Interfaces can inherit from multiple interfaces Interfaces can inherit from multiple interfaces

Classes and structs can inherit from Classes and structs can inherit from multiple interfacesmultiple interfaces

Page 6: OOPs.ppt

Classes and StructsClasses and StructsSimilaritiesSimilarities

Both are user-defined typesBoth are user-defined types

Both can containBoth can containData Data

Fields, constants, events, arraysFields, constants, events, arrays

Functions Functions Methods, properties, indexers, operatorsMethods, properties, indexers, operators

Constructors, finalizersConstructors, finalizers

Type definitionsType definitionsClasses, structs, enums, interfaces, delegatesClasses, structs, enums, interfaces, delegates

Both can implement multiple interfacesBoth can implement multiple interfaces

Both are instantiated with Both are instantiated with newnew operator operator

Page 7: OOPs.ppt

ClassClass StructStruct

Reference typeReference type Value typeValue type

Can inherit from any Can inherit from any non-sealed reference classnon-sealed reference class

No inheritanceNo inheritance(inherits only from (inherits only from System.ValueTypeSystem.ValueType))

Can have a finalizerCan have a finalizer No finalizerNo finalizer

Can have user-defined Can have user-defined parameterless constructorparameterless constructor No user-defined parameterless constructorNo user-defined parameterless constructor

Classes and StructsClasses and StructsDifferencesDifferences

Page 8: OOPs.ppt

C++ StructC++ Struct C# StructC# Struct

Same as C++ class, but all members Same as C++ class, but all members are are publicpublic User-defined value typeUser-defined value type

Can be allocated on the heap, Can be allocated on the heap, on the stack or as a member on the stack or as a member (can be used as value or reference), just (can be used as value or reference), just like C++ classlike C++ class

Always allocated on the stackAlways allocated on the stack

Members are always Members are always publicpublic Members can be Members can be publicpublic, , internalinternal or or privateprivate

ClassesClasses and Structsand StructsC# Structs vs. C++ StructsC# Structs vs. C++ Structs

Very different from C++ structVery different from C++ struct

Page 9: OOPs.ppt

public class Car : Vehicle {

public enum Make { GM, Honda, BMW }

Make make;

string vid;

Point location;

Car(Make m, string vid; Point loc) {

this.make = m;

this.vid = vid;

this.location = loc;

}

public void Drive() { Console.WriteLine(“vroom”); }

}

Car c = new Car(Car.Make.BMW, “JF3559QT98”, new Point(3,7));c.Drive();

Classes and StructsClasses and StructsClassClass

Page 10: OOPs.ppt

public struct Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } }}

Point p = new Point(2,5);p.X += 100;int px = p.X; // px = 102

Classes and StructsClasses and StructsStructStruct

Page 11: OOPs.ppt

ClassesClasses and Structsand StructsStatic vs. Instance MembersStatic vs. Instance Members

By default, members are per instanceBy default, members are per instanceEach instance gets its own fieldsEach instance gets its own fields

Methods apply to a specific instanceMethods apply to a specific instance

Static members are per typeStatic members are per typeStatic methods can’t access instance dataStatic methods can’t access instance data

No No thisthis variable in static methods variable in static methods

Don’t abuse static membersDon’t abuse static membersThey are essentially object-oriented They are essentially object-oriented global data and global functionsglobal data and global functions

Page 12: OOPs.ppt

Classes and StructsClasses and StructsAccess ModifiersAccess Modifiers

Access modifiers specify who can use a type Access modifiers specify who can use a type or a memberor a member

Access modifiers control encapsulationAccess modifiers control encapsulation

Top-level types (those directly in a namespace) can be Top-level types (those directly in a namespace) can be publicpublic or or internal internal

Class members can be Class members can be publicpublic, , privateprivate, , protectedprotected, , internalinternal, or, or protected internalprotected internal

Struct members can be Struct members can be publicpublic, , privateprivate or or internalinternal

Page 13: OOPs.ppt

If the access If the access modifier ismodifier is

Then a member defined in type T and Then a member defined in type T and assembly A is accessibleassembly A is accessible

publicpublic to everyoneto everyone

privateprivate within T only (the default)within T only (the default)

protectedprotected to T or types derived from Tto T or types derived from T

internalinternal to types within Ato types within A

protected internalprotected internal to T or types derived from Tto T or types derived from Tor to types within Aor to types within A

Classes and StructsClasses and StructsAccess ModifiersAccess Modifiers

Page 14: OOPs.ppt

Classes and StructsClasses and StructsAbstract ClassesAbstract Classes

An abstract class is one that cannot An abstract class is one that cannot be instantiatedbe instantiated

Intended to be used as a base classIntended to be used as a base class

May contain abstract and non-abstract May contain abstract and non-abstract function membersfunction members

Similar to an interfaceSimilar to an interface

Cannot be sealedCannot be sealed

Page 15: OOPs.ppt

Classes and StructsClasses and StructsSealed ClassesSealed Classes

A sealed class is one that cannot be used as a base A sealed class is one that cannot be used as a base classclass

Sealed classes can’t be abstractSealed classes can’t be abstract

All structs are implicitly sealedAll structs are implicitly sealed

System.String is sealedSystem.String is sealed

Why seal a class?Why seal a class?To prevent unintended derivationTo prevent unintended derivation

Code optimizationCode optimizationVirtual function calls can be resolved at compile-timeVirtual function calls can be resolved at compile-time

Page 16: OOPs.ppt

class Person { string name; public Person(string name) { this.name = name; } public void Introduce(Person p) { if (p != this) Console.WriteLine(“Hi, I’m “ + name); }}

Classes and StructsClasses and Structsthisthis

The The thisthis keyword is a predefined variable available in keyword is a predefined variable available in non-static function members non-static function members

Used to access data and function members unambiguouslyUsed to access data and function members unambiguously

Page 17: OOPs.ppt

class Shape { int x, y; public override string ToString() { return "x=" + x + ",y=" + y; }}class Circle : Shape { int r; public override string ToString() { return base.ToString() + ",r=" + r; }}

Classes and StructsClasses and Structsbasebase

The The basebase keyword is used to access class members that keyword is used to access class members that are hidden by similarly named members of the current are hidden by similarly named members of the current classclass

Page 18: OOPs.ppt

Classes and StructsClasses and StructsFieldsFields

A field is a member variableA field is a member variable

Holds data for a class or structHolds data for a class or struct

Can hold:Can hold:a reference type (e.g. class instance), a reference type (e.g. class instance),

a value type (e.g. a struct instance), or a value type (e.g. a struct instance), or

an array of class or struct instances an array of class or struct instances (an array is actually a reference)(an array is actually a reference)

Page 19: OOPs.ppt

public class MyClass { public const string version = “1.0.0”; public const string s1 = “abc” + “def”; public const int i3 = 1 + 2; public const double PI_I3 = i3 * Math.PI; public const double s = Math.Sin(Math.PI); //ERROR ...}

Classes and StructsClasses and StructsConstantsConstants

A constant is a data member that is evaluated at A constant is a data member that is evaluated at compile-time and is implicitly static (per type)compile-time and is implicitly static (per type)

e.g. e.g. Math.PIMath.PI

Page 20: OOPs.ppt

Classes and StructsClasses and StructsReadonly FieldsReadonly Fields

Similar to a const, but is initialized at Similar to a const, but is initialized at run-time in its declaration or in a constructorrun-time in its declaration or in a constructor

Once initialized, it cannot be modifiedOnce initialized, it cannot be modified

Differs from a constant Differs from a constant Initialized at run-time (vs. compile-time)Initialized at run-time (vs. compile-time)

Don’t have to re-compile clientsDon’t have to re-compile clients

Can be static or per-instanceCan be static or per-instance

public class MyClass { public static readonly double d1 = Math.Sin(Math.PI); public readonly string s1; public MyClass(string s) { s1 = s; } }

Page 21: OOPs.ppt

public class Button: Control { private string _caption; public string caption { get { return _caption; } set { _caption = value; Repaint(); } }} Button b = new Button();

b.caption = "OK";String s = b.caption;

Classes and StructsClasses and StructsPropertiesProperties

A property is a virtual fieldA property is a virtual field

Looks like a field, but is implemented with codeLooks like a field, but is implemented with code

Page 22: OOPs.ppt

public class Personpublic class Person{{ private int age;private int age;

public int Age {public int Age { get { return age; }get { return age; } set { age = set { age = valuevalue;; Console.WriteLine(age); Console.WriteLine(age);

}} }}}}

Person p = new Person();Person p = new Person();p.Age = 27;p.Age = 27;p.Age++;p.Age++;

PropertiesProperties

Access to private fields normally requires accessors and mutatorsAccess to private fields normally requires accessors and mutators

Properties allow access to private fields as if they were publicProperties allow access to private fields as if they were public

Person p = new Person();Person p = new Person();p.setAge(27);p.setAge(27);p.setAge(p.getAge() + 1);p.setAge(p.getAge() + 1);

instead of:instead of:PropertyProperty

C#C#

OtherOther

Page 23: OOPs.ppt

Classes and StructsClasses and StructsPropertiesProperties

Properties can be:Properties can be:Read-only (implement only Read-only (implement only getget))

Not the same as a Not the same as a readonlyreadonly field field

Write-only (implement only Write-only (implement only setset) )

Read/write (implement both Read/write (implement both getget and and setset))

Page 24: OOPs.ppt

public class ListBox: Control { private string[] _items; public string this[int index] { get { return _items[index]; } set { _items[index] = value; Repaint(); } }}

ListBox listBox = new ListBox();listBox[0] = "hello";Console.WriteLine(listBox[0]);

Classes and StructsClasses and StructsIndexersIndexers

An indexer lets an instance behave as a An indexer lets an instance behave as a virtual arrayvirtual array

Can be overloaded Can be overloaded (e.g. index by (e.g. index by intint and by and by stringstring))

Can be Can be read-only, read-only, write-only, write-only, or read/writeor read/write

Page 25: OOPs.ppt

IndexersIndexers

Index an object as if it were an arrayIndex an object as if it were an array

public class numberspublic class numbers{{ private int[3] nums;private int[3] nums;

public int this[int index] public int this[int index] {{ get { return nums[index]; }get { return nums[index]; } set { nums[index] = value; }set { nums[index] = value; } }}}}

Numbers Num = new NumbersNumbers Num = new Numbers()();;Num[0] = 5;Num[0] = 5;int Val = Num[0];int Val = Num[0];

Numbers Num = new NumbersNumbers Num = new Numbers()();;Num.Set_Nums(0,5);Num.Set_Nums(0,5);int Val = Num.Get_Nums(0);int Val = Num.Get_Nums(0);

instead of:instead of:

IndexerIndexer

C#C#

OtherOther

Page 26: OOPs.ppt

Classes and StructsClasses and StructsMethodsMethods

All code executes in a methodAll code executes in a methodConstructors, finalizers and operators are special types of Constructors, finalizers and operators are special types of methodsmethods

Properties and indexers are implemented with Properties and indexers are implemented with get/set methodsget/set methods

Methods have argument listsMethods have argument lists

Methods contain statementsMethods contain statements

Methods can return a valueMethods can return a valueOnly if return type is not Only if return type is not voidvoid

Page 27: OOPs.ppt

Classes and StructsClasses and StructsMethod Argument PassingMethod Argument Passing

By default, data is passed by valueBy default, data is passed by value

A copy of the data is created and passed A copy of the data is created and passed to the methodto the method

For value types that are passed by value, variables For value types that are passed by value, variables cannot be modified by a method callcannot be modified by a method call

For reference types that are passed by value, the For reference types that are passed by value, the instance can be modified by a method call, but the instance can be modified by a method call, but the variable itself cannot be modified by a method callvariable itself cannot be modified by a method call

Page 28: OOPs.ppt

void RefFunction(ref int p) { p++;} int x = 10;

RefFunction(ref x);// x is now 11

Classes and StructsClasses and StructsMethod Argument PassingMethod Argument Passing

The The refref modifier causes arguments to be passed by reference modifier causes arguments to be passed by reference

Allows a method call to modify a variableAllows a method call to modify a variable

Applies to both value and reference typesApplies to both value and reference types

Have to use Have to use refref modifier in method definition modifier in method definition andand in the code that calls itin the code that calls it

Variable has to have a value before callVariable has to have a value before call

Page 29: OOPs.ppt

void OutFunction(out int p) { p = 22;}

int x;OutFunction(out x);// x is now 22

Classes and StructsClasses and StructsMethod Argument PassingMethod Argument Passing

The The outout modifier causes arguments to be passed out by modifier causes arguments to be passed out by referencereference

Allows a method call to initialize a variableAllows a method call to initialize a variable

Have to use Have to use outout modifier in method definition and the modifier in method definition and the code that calls itcode that calls it

Argument has to have a value before returningArgument has to have a value before returning

Page 30: OOPs.ppt

void Print(int i);void Print(string s);void Print(char c);void Print(float f);int Print(float f); // Error: duplicate signature

Classes and StructsClasses and StructsOverloaded MethodsOverloaded Methods

A type may overload methods, i.e. provide multiple methods with A type may overload methods, i.e. provide multiple methods with the same namethe same name

Each must have a unique signatureEach must have a unique signature

Signature is based upon arguments only, the return value is Signature is based upon arguments only, the return value is ignoredignored

Page 31: OOPs.ppt

int Sum(params int[] intArr) { int sum = 0; foreach (int i in intArr) sum += i; return sum;}

int sum = Sum(13,87,34);

Classes and StructsClasses and StructsParameter ArraysParameter Arrays

Methods can have a variable number of arguments, Methods can have a variable number of arguments, called a parameter arraycalled a parameter array

paramsparams keyword declares parameter array keyword declares parameter array

Must be the last argumentMust be the last argument

Page 32: OOPs.ppt

Classes and StructsClasses and StructsAbstract MethodsAbstract Methods

An abstract method is virtual and has no implementationAn abstract method is virtual and has no implementation

Must belong to an abstract classMust belong to an abstract class

Intended to be implemented in a derived classIntended to be implemented in a derived class

Page 33: OOPs.ppt

abstract class Shape { public abstract void Draw();}class Box : Shape { public override void Draw() { ... }}class Sphere : Shape { public override void Draw() { ... }}

void HandleShape(Shape s) { s.Draw(); ...}

HandleShape(new Box());HandleShape(new Sphere());HandleShape(new Shape()); // Error!

Classes and StructsClasses and StructsAbstract MethodsAbstract Methods

Page 34: OOPs.ppt

Classes and StructsClasses and StructsOverloaded vs. Overridden MethodsOverloaded vs. Overridden Methods

Unlike method overriding, method overloading depends upon the type of the Unlike method overriding, method overloading depends upon the type of the variable, NOT on the type of the objectvariable, NOT on the type of the object

Method overloading is resolved at compile-timeMethod overloading is resolved at compile-time

However, at run-time, if the overloaded method is virtual, then the method that However, at run-time, if the overloaded method is virtual, then the method that is called is determined by the type of the objectis called is determined by the type of the object

Method overriding is resolved at run-timeMethod overriding is resolved at run-time

Page 35: OOPs.ppt

Classes and StructsClasses and StructsMethod VersioningMethod Versioning

Must explicitly use Must explicitly use overrideoverride or or newnew keywords to keywords to specify versioning intentspecify versioning intent

Avoids accidental overridingAvoids accidental overriding

Methods are non-virtual by defaultMethods are non-virtual by default

C++ and Java produce fragile base classes – C++ and Java produce fragile base classes – cannotcannot specify versioning intentspecify versioning intent

Page 36: OOPs.ppt

Method Versioning in C#Method Versioning in C#

class Derived : Base // v1.0class Derived : Base // v1.0{{ public virtual void Foo() public virtual void Foo() {{ Console.WriteLine("Derived.Foo"); Console.WriteLine("Derived.Foo"); }}}}

class Base // v1.0class Base // v1.0{{}}

class Base class Base // v2.0 // v2.0 {{ public virtual void Foo() public virtual void Foo() {{ Database.Log("Base.Foo"); Database.Log("Base.Foo"); }}}}

class Base class Base // v2.0 // v2.0 {{ public virtual public virtual intint Foo() Foo() {{ Database.Log("Base.Foo"); return 0; Database.Log("Base.Foo"); return 0; }}}}

class Derived : Base // v2.0class Derived : Base // v2.0{{ public public newnew virtual void Foo() virtual void Foo() {{ Console.WriteLine("Derived.Foo"); Console.WriteLine("Derived.Foo"); }}}}

class Derived : Base // v2.0class Derived : Base // v2.0{{ public public overrideoverride void Foo() void Foo() {{ super.Foo();super.Foo(); Console.WriteLine("Derived.Foo"); Console.WriteLine("Derived.Foo"); }}}}

Page 37: OOPs.ppt

Classes and StructsClasses and StructsConstructorsConstructors

Instance constructors are special methods that are called when a class or struct is instantiatedInstance constructors are special methods that are called when a class or struct is instantiated

Performs custom initializationPerforms custom initialization

Can be overloadedCan be overloaded

If a class doesn’t define any constructors, an implicit parameterless constructor is createdIf a class doesn’t define any constructors, an implicit parameterless constructor is created

Cannot create a parameterless constructor Cannot create a parameterless constructor for a structfor a struct

All fields initialized to zero/nullAll fields initialized to zero/null

Page 38: OOPs.ppt

Classes and StructsClasses and StructsConstructorsConstructors

Order of construction:Order of construction:1.1. Instance variables are initializedInstance variables are initialized

2.2. Base constructor is calledBase constructor is called

3.3. Body of constructor is calledBody of constructor is called

All during construction the object is considered to be the constructed typeAll during construction the object is considered to be the constructed typeAvoid calling virtual methods in constructorsAvoid calling virtual methods in constructors

The object may not be property initializedThe object may not be property initialized

This is like Java, but unlike C++This is like Java, but unlike C++

Page 39: OOPs.ppt

class B { private int h; public B() { } public B(int h) { this.h = h; }}class D : B { private int i; public D() : this(24) { } public D(int i) { this.i = i; } public D(int h, int i) : base(h) { this.i = i; }}

Classes and StructsClasses and StructsConstructor InitializersConstructor Initializers

One constructor can call another with a constructor One constructor can call another with a constructor initializerinitializer

Can call Can call this(...)this(...) or or base(...)base(...)

Default constructor initializer is Default constructor initializer is base()base()

Page 40: OOPs.ppt

Classes and StructsClasses and StructsStatic ConstructorsStatic Constructors

A static constructor lets you create initialization code that is called once for the classA static constructor lets you create initialization code that is called once for the class

Guaranteed to be executed before the first instance of a class or struct is created and before any Guaranteed to be executed before the first instance of a class or struct is created and before any static member of the class or struct static member of the class or struct is accessedis accessed

No other guarantees on execution orderNo other guarantees on execution order

Only one static constructor per typeOnly one static constructor per type

Must be parameterlessMust be parameterless

Page 41: OOPs.ppt

class Foo { ~Foo() { Console.WriteLine(“Destroyed {0}”, this); }}

Classes and StructsClasses and StructsFinalizersFinalizers

A finalizer is a method that is called before an instance is garbage collectedA finalizer is a method that is called before an instance is garbage collectedDifferent from a C++ destructorDifferent from a C++ destructor

Used to clean up any resources held by the instance, do bookkeeping, etc. Used to clean up any resources held by the instance, do bookkeeping, etc.

Only classes, not structs, can have finalizersOnly classes, not structs, can have finalizers

Page 42: OOPs.ppt

Classes and StructsClasses and StructsFinalizersFinalizers

Unlike C++, C# finalizers are non-deterministicUnlike C++, C# finalizers are non-deterministic

They are not guaranteed to be called at a specific time (i.e. they aren’t called when They are not guaranteed to be called at a specific time (i.e. they aren’t called when an instance goes out of scope)an instance goes out of scope)

They are guaranteed to be called before shutdown (...kind of)They are guaranteed to be called before shutdown (...kind of)

Use the Use the usingusing statement and the statement and the IDisposableIDisposable interface to achieve interface to achieve deterministic finalizationdeterministic finalization

Page 43: OOPs.ppt

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

Classes and StructsClasses and StructsOperator OverloadingOperator Overloading

User-defined operatorsUser-defined operators

Must be a static methodMust be a static method

Page 44: OOPs.ppt

Classes and StructsClasses and StructsOperator OverloadingOperator Overloading

++ -- !! ~~

truetrue falsefalse ++++ ----

Overloadable unary operatorsOverloadable unary operators

Overloadable binary operatorsOverloadable binary operators

++ -- ** // !! ~~

%% && || ^̂ ==== !=!=

<<<< >>>> << >> <=<= >=>=

Page 45: OOPs.ppt

Classes and StructsClasses and StructsOperator OverloadingOperator Overloading

No overloading for member access, method invocation, No overloading for member access, method invocation, assignment operators, nor these operators: assignment operators, nor these operators: sizeofsizeof, , newnew, , isis, , asas, , typeoftypeof, , checkedchecked, , uncheckedunchecked, , &&&&, , ||||, , and and ?:?:

The The &&&& and and |||| operators are automatically evaluated operators are automatically evaluated from from && and and ||

Overloading a binary operator (e.g. Overloading a binary operator (e.g. **) implicitly overloads ) implicitly overloads the corresponding assignment operator (e.g. the corresponding assignment operator (e.g. *=*=))

Page 46: OOPs.ppt

Classes and StructsClasses and StructsOperator OverloadingOperator Overloading

struct Vector { int x, y; public Vector(x, y) { this.x = x; this.y = y; } public static Vector operator +(Vector a, Vector b) { return Vector(a.x + b.x, a.y + b.y); } ...}

ExampleExample

Page 47: OOPs.ppt

class Note { int value; // Convert to hertz – no loss of precision public static implicit operator double(Note x) { return ...; } // Convert to nearest note public static explicit operator Note(double x) { return ...; }}

Note n = (Note)442.578;double d = n;

Classes and StructsClasses and StructsConversion OperatorsConversion Operators

User-defined explicit and implicit conversionsUser-defined explicit and implicit conversions

Page 48: OOPs.ppt

Classes and StructsClasses and Structsisis Operator Operator

The The isis operator is used to dynamically test if the run- operator is used to dynamically test if the run-time type of an object is compatible with a given typetime type of an object is compatible with a given type

static void DoSomething(object o) { if (o is Car) ((Car)o).Drive();}

Don’t abuse the Don’t abuse the isis operator: it is preferable to design an operator: it is preferable to design an appropriate type hierarchy with polymorphic methodsappropriate type hierarchy with polymorphic methods

Page 49: OOPs.ppt

Classes and StructsClasses and Structsasas Operator Operator

The The asas operator tries to convert a variable to a specified operator tries to convert a variable to a specified type; if no such conversion is possible the result is type; if no such conversion is possible the result is nullnull

static void DoSomething(object o) { Car c = o as Car; if (c != null) c.Drive();}

More efficient than using More efficient than using isis operator: test and convert in operator: test and convert in one operationone operation

Same design warning as with the Same design warning as with the isis operator operator

Page 50: OOPs.ppt

Classes and StructsClasses and Structstypeoftypeof Operator Operator

The The typeoftypeof operator returns the operator returns the System.TypeSystem.Type object object for a specified typefor a specified type

Can then use reflection to dynamically obtain information Can then use reflection to dynamically obtain information about the typeabout the type

Use Use GetType()GetType() to get the type of an instance to get the type of an instance

Console.WriteLine(typeof(int).FullName);Console.WriteLine(typeof(System.Int32).Name);Console.WriteLine(typeof(float).Module);Console.WriteLine(typeof(double).IsPublic);Console.WriteLine(typeof(Car).MemberType);

Page 51: OOPs.ppt

AgendaAgenda

Review Object-Oriented ConceptsReview Object-Oriented Concepts

InterfacesInterfaces

Classes and StructsClasses and Structs

DelegatesDelegates

EventsEvents

Page 52: OOPs.ppt

DelegatesDelegatesObject oriented function pointersObject oriented function pointers

A reference type encapsulating a method signature and return valueA reference type encapsulating a method signature and return value

Can point to multiple functionsCan point to multiple functionsThread-safe + and - operationsThread-safe + and - operations

Foundation for eventsFoundation for events

delegate double Func(double x);delegate double Func(double x);

Func func = new Func(Math.Sin);Func func = new Func(Math.Sin);double x = func(1.0);double x = func(1.0);

public class math {public class math { double Sin(double x)double Sin(double x) {{ //return (sin x) //return (sin x) }}}}

delegate void Greeting();delegate void Greeting();

Greeting greeting; Greeting greeting; greeting += new Greeting(A.SayHello);greeting += new Greeting(A.SayHello);greeting += new Greeting(A.Bow);greeting += new Greeting(A.Bow);

public class a public class a {{ void SayHello() { //Say Hello }void SayHello() { //Say Hello } void Bow() { // bow }void Bow() { // bow }}}

DelegateDelegate Multicast DelegateMulticast Delegate

Page 53: OOPs.ppt

AgendaAgenda

Review Object-Oriented ConceptsReview Object-Oriented Concepts

InterfacesInterfaces

Classes and StructsClasses and Structs

DelegatesDelegates

EventsEvents

Page 54: OOPs.ppt

Events Events

Specialized multicast delegateSpecialized multicast delegate

Represent a signal that something has occurred in a Represent a signal that something has occurred in a programprogram

Two main issuesTwo main issuesGenerating eventsGenerating events

Consuming eventsConsuming events

Page 55: OOPs.ppt

EventsEventsOverviewOverview

C# has native support for eventsC# has native support for events

Based upon delegatesBased upon delegates

An event is essentially a field holding a delegateAn event is essentially a field holding a delegate

However, public users of the class can only register However, public users of the class can only register delegatesdelegates

They can only call They can only call +=+= and and -=-=

They They cannotcannot invoke the event’s delegate invoke the event’s delegateOnly the object containing the event can invoke the delegateOnly the object containing the event can invoke the delegate

Multicast delegates allow multiple objects to register with Multicast delegates allow multiple objects to register with the same eventthe same event

Page 56: OOPs.ppt

EventsEvents

Create a Type defining the information to be passed to Create a Type defining the information to be passed to receivers of the event.receivers of the event.

public class MailManagerpublic class MailManager{{ public class MailMsgEventArgs : EventArgs { public class MailMsgEventArgs : EventArgs { public readonly string from, to, body;public readonly string from, to, body;

public MailMsgEventArgs(string From, string To, string public MailMsgEventArgs(string From, string To, string Body) {Body) {

this.from = From;this.from = From; this.to = To;this.to = To; this.body = Body;this.body = Body;

}} }}}}

Page 57: OOPs.ppt

Events Events SourcingSourcing

Define the event signatureDefine the event signature

Define the event and firing logicDefine the event and firing logic

public delegate void MailMsgEventHandler(object sender, public delegate void MailMsgEventHandler(object sender, MailMsgEventArgs e);MailMsgEventArgs e);

public class MailManagerpublic class MailManager{{ public event MailMsgEventHandler MessageReceived; public event MailMsgEventHandler MessageReceived;

protected void OnMessageReceived(MailMsgEventArgs e) {protected void OnMessageReceived(MailMsgEventArgs e) { if (MessageReceived != null) if (MessageReceived != null)

MessageReceived(this, e);MessageReceived(this, e); } }}}

Page 58: OOPs.ppt

EventsEvents

Create a Method that is responsible for raising the event.Create a Method that is responsible for raising the event.

public void SimulateArrivingMsg (string from, string to, public void SimulateArrivingMsg (string from, string to, string body) {string body) { MailMsgEventArgs e = new MailMsgEventArgs(from, to, body); MailMsgEventArgs e = new MailMsgEventArgs(from, to, body);

OnMailMessageReceived(e);OnMailMessageReceived(e);}}

Page 59: OOPs.ppt

Events Events HandlingHandling

Define and register event handlerDefine and register event handler

public class MyForm: Formpublic class MyForm: Form{{ MailManager FaxApplication;MailManager FaxApplication;

public MyForm() {public MyForm() { FaxApplication = new MailManager();FaxApplication = new MailManager(); FaxApplication.MessageReceived += new FaxApplication.MessageReceived += new MailMsgEventHandler(FaxMsg);MailMsgEventHandler(FaxMsg); }}

void FaxMsg(object sender, MailMsgEventArgs e) {void FaxMsg(object sender, MailMsgEventArgs e) { MessageBox.Show("You recd a msg from “ + e.from);MessageBox.Show("You recd a msg from “ + e.from); }}}}

Page 60: OOPs.ppt

AttributesAttributes

How do you associate information with types and How do you associate information with types and members?members?

Documentation URL for a classDocumentation URL for a class

Transaction context for a methodTransaction context for a method

XML persistence mappingXML persistence mapping

Traditional solutionsTraditional solutionsAdd keywords or pragmas to languageAdd keywords or pragmas to language

Use external files, e.g., IDL, DEFUse external files, e.g., IDL, DEF

C# solution: AttributesC# solution: Attributes

Page 61: OOPs.ppt

AttributesAttributes

Appear in square bracketsAppear in square brackets

Attached to code elementsAttached to code elements

[HelpUrl(“http://SomeUrl/Docs/SomeClass”)][HelpUrl(“http://SomeUrl/Docs/SomeClass”)]class SomeClassclass SomeClass{{ [WebMethod][WebMethod] void GetCustomers() { … }void GetCustomers() { … }

string Test([SomeAttr] string param1) {…}string Test([SomeAttr] string param1) {…}}}

Page 62: OOPs.ppt

Attribute Fundamentals Attribute Fundamentals Can be Intrinsic or CustomCan be Intrinsic or Custom

Attributes are generic classes!Attributes are generic classes!

Easy to attach to types and membersEasy to attach to types and members

Attributes can be queried at runtimeAttributes can be queried at runtime

class HelpUrl : System.Attribute { class HelpUrl : System.Attribute { public HelpUrl(string url) { … }public HelpUrl(string url) { … } … …}}

[HelpUrl(“http://SomeUrl/APIDocs/SomeClass”)][HelpUrl(“http://SomeUrl/APIDocs/SomeClass”)]class SomeClass { … }class SomeClass { … }

Type type = Type.GetType(“SomeClass”);Type type = Type.GetType(“SomeClass”);

Attribute[] attributes = Attribute[] attributes = type.GetCustomAttributes();type.GetCustomAttributes();

Page 63: OOPs.ppt

Creating AttributesCreating Attributes

Attributes are simply classesAttributes are simply classesDerived from System.AttributeDerived from System.Attribute

Class functionality = attribute functionalityClass functionality = attribute functionality

public class HelpURLAttribute: System.Attributepublic class HelpURLAttribute: System.Attribute{{

public HelpURLAttribute(string url) { … }public HelpURLAttribute(string url) { … }

public string URL { get { … } }public string URL { get { … } }public string Tag { get { … } set { … } }public string Tag { get { … } set { … } }

}}

Page 64: OOPs.ppt

Using AttributesUsing Attributes

Just attach it to a classJust attach it to a class

Use named parametersUse named parameters

Use multiple attributesUse multiple attributes

[HelpURL(“[HelpURL(“http://someurl/”)]”)]Class MyClass { … }Class MyClass { … }

[HelpURL(“[HelpURL(“http://someurl/”, Tag=“ctor”)]”, Tag=“ctor”)]Class MyClass { … }Class MyClass { … }

[HelpURL(“[HelpURL(“http://someurl/”),”), HelpURL(“http://someurl/”, Tag=“ctor”)]HelpURL(“http://someurl/”, Tag=“ctor”)]Class MyClass { … }Class MyClass { … }

Page 65: OOPs.ppt

Querying AttributesQuerying Attributes

Use reflection to query attributesUse reflection to query attributes

Type type = typeof(MyClass);Type type = typeof(MyClass);

foreach(object attr in type.GetCustomAttributes())foreach(object attr in type.GetCustomAttributes()){{ if(attr is HelpURLAttribute)if(attr is HelpURLAttribute) {{ HelpURLAttribute ha = (HelpURLAttribute) HelpURLAttribute ha = (HelpURLAttribute) attr;attr; myBrowser.Navigate(ha.URL);myBrowser.Navigate(ha.URL); }}}}