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

Interfaces 1

C# 30

C# 3.0
Chapter 12 Interfaces

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 2

C# 30

A Web Browser Example


Imagine that you are developing a Web
Browser
Your browser should display many types of contents
Text, Sound, animation, video and other objects
You are absolutely not interested in the objects
implementation details
You just require that any such object implement
certain methods required by the web browser to
enable
bl the
th ititems
handling
h dli

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 3

C# 30

A Web Browser Example


Suppose our simple browser need only
these operations from each element:
Load to be activated when the page comes up
Play to be activated when the user clicks on the
item

You are looking


g for a feature in the
language that will allow you to define the
set of methods you require from any type
that wants its objects to integrate into your
application
li ti

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 4

C# 30

Interfaces Introduction
Yo
You want
ant this ffunctionality
nctionalit to serve
ser e as a
contract:
A type that claims to adhere to the contract must actually
p
all the methods defined in the contract
implement
As a client that uses such a class, you want to be ensured
that all methods are implemented according to their
definition in the contract

The C# feature that should be used for


defining such a contract is the interface
interfa e

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 5

C# 30

The Web Browser Example


We define a Web Page class
The web page defines an interface:
interfaceIEmbeddable {
voidLoad();
()
voidPlay();
}

The Web Page contains a collection of IEmbeddable


classWebPage
l
b
{
privateList<IEmbeddable>_items=
newList<IEmbeddable>();
publicvoidAdd(IEmbeddable item){
_items.Add(item);
}
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 6

C# 30

The Web Browser Example


The AnimationObj type claims to
the IEmbeddable interface:
implement
p
classAnimationObj :IEmbeddable
{
publicvoidLoad()
{//}
publicvoidPlay()
{// }
{//}
publicvoidDraw()
{//}
}

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 7

C# 30

The Web Browser Example


It is therefore possible to add an
AnimationObj
j item to the web page:
p g
classWebPageApp {
staticvoidMain(){
() {
AnimationObj animator=newAnimationObj();
animator Dra ()
animator.Draw();
animator.Play();
//
//
WebPage page=newWebPage();
pa e Add(ani ator)
page.Add(animator);
//
}
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 8

C# 30

Interfaces Vs.
Vs Abstract Class
Looking at an interface definition
Isnt it actually a class?
To be more specific, an abstract base class that contains
only pure virtual methods?

The main distinction between a class and


an interface is:
A class is an entity,
probably representing an entity in the application domain
The class is composed of operations and data

An interface
f
is only a behavior definition
f
A set of related abilities, just signatures, with no
iimplementation
l
t ti
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 9

C# 30

Interfaces Vs.
Vs Base Class
A base class will
ill be defined either as
as:
A regular class : providing common functionality,
or as an interface: defining behavior only

In addition:
A derived class extends a base class
It extends and specializes its base structure and functionality

A class implements an interface


It provides its way of implementing the general behavior
defined in the interface

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 10

C# 30

Interface Declaration
In C#,
C# an interface is not a class with
ith
p
characteristics
special
It is a first-class built-in concept
having rules and conventions for definition and
implementation

A
An interface
i t f
iis d
defined
fi d using
i th
the kkeyword
d
interface
By convention, its name should be preceded with a
capital I
I followed by the interface name with the first
letter capitalized
IEmbeddable,IEnumerable
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 11

C# 30

Interface Declaration
An interface can contain methods
methods,
properties, indexers and events, none of
which
hi h are iimplemented
l
t d iin th
the iinterface
t f
itself
An interface is a reference type that is never directly
p
created and has no actual representation
Interface method declarations should not be prefixed
with an access modifier
They are all, by default, public
Interface methods are all,, byy default,, pure
p
virtual
methods

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 12

C# 30

Interface Declaration
An interface can contain also properties
properties,
indexers and events
The following is an enhanced version of the
IEmbeddable interface
interfaceIEmbeddable
{
voidLoad();
voidPlay();
y();
stringTitle{get;}
tCli k dE
t Clicked;
Cli k d
eventClickedEvent
stringthis[int index]{get;set;}
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 13

C# 30

Interface Implementation
A class that is defined to implement an
interface must define all members
declared in the interface:
Interface method signatures cannot be modified
Interface methods must be defined as public
Interface methods can be defined to be virtual

The compiler ensures that an


implementing class actually adheres to its
i t f
interface
contract
t t
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 14

C# 30

Using the Implemented Item


Instances of a class can be used by the
client that requires the general interface
with no assumptions on the specific types that
implement it
They are called through a reference to the interface:
publicvoidLoad()
p
()
{
foreach(IEmbeddable iteminitems)
item.Load();
}

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 15

C# 30

Inheritance and Interface


Consider the following graphical system:
The shapes class hierarchy is composed of:

An abstract
A
b t t base
b
class
l
Shape,
h
d fi i shapes
defining
h
common
fields position and methods Draw(),Resize() and
Move()
()
Three derived classes : Circle, Rectangle and
Triangle, each overrides required methods as well as
adding its specific functionality

A Desktop class is defined to manage shapes

It contains a list of shapes: List<Shape> _shapes


It enables several operations, common to all shapes, to be
obtained on the stored shapes

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 16

C# 30

A Graphical System Example


publicabstractclassShape{//}
publicclassCircle:Shape{//}
publicclassRectangle:Shape{//}
publicclassTriangle:Shape{//}
publicclassDesktop
{
privateList<Shape>_shapes=newList<Shape>;
privateList<Shape> shapes=newList<Shape>;
publicShapethis[int index]//indexeronshapes
{//}
publicbool Add(Shapeshape)
{//}
}

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 17

C# 30

A Graphical System Example


Later
Later, a new shape behavior was defined
The ability to be drawn in 3D:
publicinterfaceIDraw3D
{
voidDraw3D();
();
}

Two of the shape classes chose to implement it:


publicclassCircle:
Shape IDraw3D
Shape,IDraw3D
{
publicvoidDraw3D()
publicvoidDraw3D()...
}

publicclassRectangle:
Shape IDraw3D
Shape,IDraw3D
{
publicvoidDraw3D()
publicvoidDraw3D()...
}

The new functionality


Th
f
ti
lit was applied
li d to
t some off the
th shape
h
classes without interfering with the overall hierarchy
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 18

C# 30

A Graphical System Example


The Desktop added a method to enable
activating the 3D draw:
But how should the Draw3D() be defined?

Lets
Let s start with a simple attempt:

publicbool Draw3D(int index)


{
if(index>=_shapes.Count)
thrownewIndexOutOfRangeException();
_shapes[index].Draw3D()
h
[i d ] D
3D()
//
}

Can you find any problems with this definition?


Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 19

C# 30

A Graphical System Example


The statement _shapes[index].Draw3D()
shapes[index] Draw3D()
Gets the following compile error:
'Shape'doesnotcontainadefinitionfor'Draw3D'

Our previous WebPage class,


class stored its items in an
IEmbeddable reference list
ensuring all stored items implement IEmbeddable

The Desktop class, however, stores its shapes in a


more heterogeneous array: a Shape reference list
Only Shape class methods can be directly applied on Shape
references
The Draw3D()method can only be activated through an
IDraw3Dreference
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 20

C# 30

A Graphical System Example


Lets cast!
publicbool Draw3D(int index)
{
//
//
IDraw3DthreeDShape =(IDraw3D)_shapes[index];
threeDShape.Draw3D();
//
}

How about this?

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 21

C# 30

Querying for Implementation


The second Draw3D() version would
compile
However, when an index of a shape that does not
implement the IDraw3D interface is provided, a runtime exception InvalidCastException
I
lidC tE
ti is thrown

We need to find out if the required shape


is of a type that implements IDraw3D
We can use the operators is and as to query an
object if it implements a specified interface
IDraw3DthreeDShape
ID
3Dth
DSh
=_shapes[i]asIDraw3D;
h
[i] ID
3D
if(threeDShape !=null)
threeDShape.Draw3D();
p
();
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

C# 30

Interfaces 22

Inheritance / Interface Riddle


The IDraw3D
IDra 3D interface presented above
contained a single
g method named:
Draw3D()
What would happen if the interfaces definers would
have called their method merely Draw()?
D
()?
Do you see the problem that would arise in such a
situation?

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 23

C# 30

The Name Collision Problem


Lets
Let s revisit the Circle class definition:
publicclassCircle:Shape,IDraw3D
{//
publicvoidDraw3D(){//}
}

() is the Circle class defining?


g
Which Draw()
The base Shape Draw(), or the IDraw3DDraw()?

Can the class implement both definitions


of the method only once?
And if so
so, the method has a completely different
meaning in the different contexts

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 24

C# 30

The Name Collision Problem


In the current Circle class definition:
the Draw()method will be executed, both when
activated in a Circle object (or Shape) context:
Circlecircle =newCircle(5,10,15);
circle Draw();
circle.Draw();

And in a IDraw3D context:


IDraw3DthreeDShape =_shapes[index]asIDraw3D;
if(threeDShape!=null)
threeDShape.Draw();

We would like to be able to define two


versions of the Draw() method
and to ensure that each will be called in its context
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 25

C# 30

Explicit Interface Specification


When implementing an interface method
It is possible to explicitly specify the name of the
interface to which the method belongs:
publicclassCircle:Shape,IDraw3D
{
publicoverridevoidDraw()
{
Console.Writeline("Iama2Dcircle!");
}
voidIDraw3D.Draw()
{
Console Writeline("IamaBall!");
Console.Writeline("IamaBall!");
}
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 26

C# 30

The System Interfaces


Being a key concept
concept, interfaces plays an
important role in the .NET framework
There are several pre-defined interfaces

The String class, for example, supports


several members such as:
Concat()
Concat(), Replace()and Length
In addition, it implements several interfaces:
publicsealedclassString:
IComparable,ICloneable,IConvertible,
IComparable<string>,IEnumerable<char>,
IEnumerable,IEquatable<string>

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 27

C# 30

Interfaces: Another Viewpoint


Interfaces provide
pro ide us
s with
ith the means for
generic p
g
programming
g
g
Using interfaces, we can provide general algorithms
as type independent services

For example, a sort algorithm can be


applied to any type, so long as it provides
an appropriate comparison method
How will we define this requirement?
How
Ho will
ill it be enforced on instances pro
provided
ided as
arguments to our algorithm?
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 28

C# 30

The IComparable Interface


The IComparable interface is actually the
p
.NET version of the theoretical comparison
interface idea we have just presented
While learning about the .NET
NET array
array, we realized that
the Array class provides a sorting method
We
W used
d it tto sortt an array holding
h ldi integers
i t
Can this method be called for an array storing any element
type?
Will it be possible, for example, to sort an array of Employee
objects?
Which compare method does the Sort() method use to
perform the sorting algorithm?
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 29

C# 30

The IComparable Interface


Tr
Trying
ing to e
execute
ec te the emplo
employees
ees program
with the following
g statements inside:
Employee[]employees=...;
//
//
Array.Sort(employees);

Generates this run time exception:


UnhandledException:
p
System.InvalidOperationException:
SpecifiedIComparer threwanexception.>
S t
System.ArgumentException:
A
tE
ti

AtleastoneobjectmustimplementIComparable.

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 30

C# 30

The IComparable Interface


IComparable is the interface that is used
to compare objects in the sorting methods
IComparable contains a single method:
int CompareTo(objectobj );
Where: obj is the object to be compared with the current
instance

The methods return value is an integer that indicates


the relative order of the compared operands
Less than zero:
Zero:
Greater than zero:

This instance is less than obj


This instance is equal to obj
This instance is greater than obj

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 31

C# 30

The IComparable Example


classEmployee:IComparable {
publicint CompareTo(objectobj){
Employeeother=(Employee)obj;
//Thedefaultsortingisbyname:
returnString.Compare(_name,other._name);
}
}
classEmployeeManager {
privateEmployee[]_employees;
publicvoidSort(){
(
)
Array.Sort(_employees);
}
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 32

C# 30

Extension Methods
Extending an Interface
//InSystem.dll
//I
S t
dll
publicinterfaceIComparable {
int CompareTo(objectobj);
p
( j
j);
}
//InMyExtensions.dll
namespaceMyExtensions
M E t
i
{
staticclassComparableExtensions {
publicstaticbool IsGreater(this
p
(
IComparable
p
obj,
j,
objectother){
returnobj.CompareTo(other)>0;
}
publicstaticbool IsEqual(this IComparable obj,
objectother){
j
) {
returnobj.CompareTo(other)==0;
}
}
}//endnamespace
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 33

C# 30

Extending
Extending an Interface
//InBigInt.dll
classBigInteger :IComparable {
//Implementation
}
//Inmycode:
usingMyExtensions;//Importextensions
BigInt b1=newBigInt(10000000);
BigInt b2=newBigInt(10000001);
b1.IsEqual(b2);//CompareExtensions.IsEqual
b1.IsGreater(b2);//CompareExtensions.IsGreater

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 34

C# 30

The IComparable<T> Interface


We will learn Generics later in this course
It is something similar to C++ templates

Using IComparable is expensive in most


cases and error prone
We have to cast from object to our type
For value types, we pay the box/unbox operations
In .NET 2.0, new generic
g
interfaces were introduced
IComparable<T> is one of them:
publicinterfaceIComparable<T>
{
(
)
int CompareTo(Tother);
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 35

C# 30

Additional Comparing Methods:


The IComparer
The IComparable interface is the default
sorting interface
The CompareTo() method therefore define the
default compare method
It is possible to provide other comparing methods, to
sort based on different sorting criteria
Thi
This can be
b d
done b
by d
defining
fi i h
helper
l
classes
l
th
thatt iimplement
l
t
the IComparer or IComparer<T> interfaces
Compare() method
An instance of such a helper class is passed as an additional
parameter to the Sort() method
When this is done
done, the provided Compare() method will be
used, instead of the default CompareTo() method
This lets us tune the sorting
dynamically
g algorithm
g
y
y
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 36

C# 30

The IEnumerable Interface


C# array
arra and collections elements can be
g the foreach construct
iterated using
Is foreach implemented specifically for the
framework collections?
Or
Does it define a general contract of which any class
that adheres to it can join the foreach game?
Can we apply the foreach
f
h statement usage on our
user-defined collection class?

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 37

C# 30

The IEnumerable Interface


Tr
Trying
ing to compile the follo
following
ing (some
(somewhat
hat
nave)) statement on our original
g
EmployeeManager class:
foreach (Employeeein_employees)
Console.WriteLine("Name:"+e.Name);

Will generate the following compile error:


foreach statementcannotoperateonvariablesof
type'employeeTools.EmployeesManager'because
type employeeTools.EmployeesManager because
'employeeTools.EmployeesManager'doesnotcontain
adefinitionfor'GetEnumerator
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 38

C# 30

The IEnumerable Interface


It seems that to use the foreach
statement
We should implement the interface: IEnumerable

The IEnumerable interface contains one


method:
IE
IEnumerator
t
G tE
GetEnumerator();
t ()

It returns an object of a type that


implements the IEnumerator interface
f

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 39

C# 30

The IEnumerator Interface


The IEnumerator interface is the actual
iteration interface, containing the following
b
members:
objectCurrent{get;}
bj tC
t{ t }
bool MoveNext();
voidReset();
();

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 40

C# 30

IEnumerable & IEnumerator


It seems that we have two separate
entities:
The container class and an enumerator class

The enumerable container does not


directly implement the enumeration
operations but rather defines a separate
operations,
enumerator class, as a nested type:
This helper class implements the actual enumeration
operations on its container
When
Wh the
th container
t i
is
i asked
k d for
f enumeration
ti services
i
(GetEnumerator()), it provides an object of its
enumerator class to be used for enumeration
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 41

C# 30

Enumerator Example
classEmployeeManager :IEnumerable
{
//
//IEnumerable requiresthisfromanenumerableclass:
//ItreturnsanobjectofIEnumerable type,
//thatprovidestheactualenumerationservices.
publicIEnumerator GetEnumerator()
{
returnnewEnumerator(employees);
}
//

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 42

C# 30

Enumerator Example
//Nestedclass
publicclassEnumerator:IEnumerator {
publicEnumerator(IList employees){
_employees=employees;
ResetCurrent();
}
publicobjectCurrent
{
get{
if(
(_cu
current==1||
e t
|| _cu
current>
e t > _e
employees.Count1)
p oyees.Cou t )
thrownewInvalidOperationException();
return_employees[current];
}
}

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 43

C# 30

Enumerator Example
publicbool MoveNext(){
if(_current<_employees.Count 1)
{
_current++;
returntrue;
}
returnfalse;
}
publicvoidReset(){ResetCurrent();}
privatevoidResetCurrent(){
_cu
current=1;
e t
;
}
privateint _current;
privateIList _employees;
}
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 44

C# 30

IEnumerable<T> IEnumerator<T>
IEnumerable<T>,IEnumerator<T>
id ttype safety
f t and
d performance:
f
T
To provide
publicinterfaceIEnumerable<T>:IEnumerable {
IEnumerator<T>GetEnumerator();
}
publicinterfaceIEnumerator<T>:
p
IDisposable,IEnumerator {
TCurrent{get;}
}

We will see these interfaces again in the


Generic Collections chapter
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 45

C# 30

Interfaces and Collections


IEnumerable and IComparable are two
examples of collection-related interfaces
The .NET framework provides several collection
classes in System.Collections.Generic
List<T>,SortedList<TKey,TValue>,Queue<T>,
i
d i
l
Stack<T>,Dictionary<TKey,TValue> and much more

All .NET
NET collections implement several interfaces that
represent basic element management, such as the
ICollection &ICollection<T>,IEnumerable
,
&
IEnumerable<T>,ICloneable interfaces

Different collections implement other, more specific


interfaces, such as: IList,IList<T> and
IDictionary,IDictionary<TKey,TValue>
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 46

C# 30

The IFormattable Interface


Recall the string formatting discussion
from the second course chapter
In this discussion we presented the ability to control
the output format of some .NET pre-defined types:
Console.WriteLine("Currencyformat:{0:C}",8888);
Console.WriteLine(Longdateformat:{0:D}",DateTime.Now);

This formatting technique was also used to output


enumerated type values as bit flags:
enum Characteristics{
Smart=0x0001,//
}
Characteristicscharacter=Characteristics.Tall |
Characteristics.Kind;
Console.WriteLine("Thecharacteris:{0:F}",character);
l
i
i (" h
h
i
{
}"
h
)
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 47

C# 30

The IFormattable Interface


Can I provide
pro ide m
my users
sers ssuch
ch control o
over
er
p format p
printing
g of my
y objects?
j
the output
Can I enable them produce different output formats
based on provided format characters?

The answer is implement IFormattable


The IFormattable Interface contains a single
method:
stringToString(stringformat,
IFormatProvider formatProvider );

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 48

C# 30

IFormattable Example
classEmployee:Iformattable {
privateint _id;
privatestring name;
privatestring_name;
privateint _salary;
privateint
p
ate
t _se
seniority;
o ty;
privatechar_gender;
//
publicoverridestringToString()
{
returnString.Format("Id:{0},Name:{1},Salary:{2}",
_id,_name,_salary);
}

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 49

C# 30

IFormattable Example
publicstringToString(stringfmt,IFormatProvider
publicstringToString(stringfmt
IFormatProvider fp)
{
switch(fmt)
{
case ( u ):
case(null):
returnToString();
case"F":
returnString.Format(...);
default:
returnToString();
}
}
}

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 50

C# 30

IFormattable Example
usingSystem;
classEmployeesApp {
staticvoidMain(){
Employeee1=newEmployee("Jack",10000,'M');
Employeee2=newEmployee("Jane",12000,'F');
Console.WriteLine("Employeeno.1{0}",e1);
Console.WriteLine("Employeeno.3{0:F}",e2);
}
}

Employeeno.1:Id:0,Name:Jack,Salary:M
p y
,
,
y
Employeeno.2:
Id:1
Name:Jane
Gender:F
Seniority:0
Salary:12000
Copyright
SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 51

C# 30

Chapter 12 Exercise 1

THE ENHANCED WEEKLY


SCHEDULE EXERCISE
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Interfaces 52

C# 30

Chapter Summary
Interfaces define contracts
Classes define behavior

Querying a type for an interface


implementation can be done with the is
and as operators
Interfaces can be explicitly implemented
.NET has many pre-defined interfaces
Many of those interfaces serve as the contract
between collections and generic algorithms

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Вам также может понравиться