Upload
karmamen
View
229
Download
0
Embed Size (px)
DESCRIPTION
p
Citation preview
Interfaces 1 C# 30
C# 3.0C# 3.0
Chapter 12 Interfaces
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
A Web Browser ExampleInterfaces 2 C# 30
A Web Browser Example Imagine that you are developing a Web 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 bl th it h dlienable the items handling
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
A Web Browser ExampleInterfaces 3 C# 30
A Web Browser Example Suppose our simple browser need only 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 for a feature in the glanguage that will allow you to define the set of methods you require from any typeset of methods you require from any type that wants its objects to integrate into your
li tiapplication
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Interfaces IntroductionInterfaces 4 C# 30
Interfaces IntroductionYo ant this f nctionalit to ser e as a You want this functionality to serve as a contract: A type that claims to adhere to the contract must actually
implement all the methods defined in the contractp 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 interfa edefining such a contract is the interface
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
The Web Browser ExampleInterfaces 5 C# 30
The Web Browser ExampleWe define a Web Page class We define a Web Page class The web page defines an interface:interfaceIEmbeddable {
voidLoad();()voidPlay();
}
The Web Page contains a collection of IEmbeddablel b {classWebPage {privateList_items=
newList();newList();publicvoidAdd(IEmbeddable item){
_items.Add(item);}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
}}
The Web Browser ExampleInterfaces 6 C# 30
The Web Browser ExampleThe AnimationObj type claims to The AnimationObj type claims to implement the IEmbeddable interface:pclassAnimationObj :IEmbeddable{{publicvoidLoad(){//}
publicvoidPlay(){// }{//}
publicvoidDraw(){//}
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
The Web Browser ExampleInterfaces 7 C# 30
The Web Browser ExampleIt is therefore possible to add an It is therefore possible to add an AnimationObj item to the web page:j p gclassWebPageApp {
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 Vs Abstract ClassInterfaces 8 C# 30
Interfaces Vs. Abstract ClassLooking at an interface definition 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:an interface is: A class is an entity,
probably representing an entity in the application domain The class is composed of operations and data
f f An interface is only a behavior definition A set of related abilities, just signatures, with no
i l t ti
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
implementation
Interfaces Vs Base ClassInterfaces 9 C# 30
Interfaces Vs. Base ClassA base class ill be defined either as A base class will be defined either as: A regular class : providing common functionality, or as an interface: defining behavior only
In addition: 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
Interface DeclarationInterfaces 10 C# 30
Interface DeclarationIn C# an interface is not a class ith In C#, an interface is not a class with special characteristicsp It is a first-class built-in concept having rules and conventions for definition and having rules and conventions for definition and
implementation
A i t f i d fi d i th k d An interface is defined using the keyword interface By convention, its name should be preceded with a
capital I followed by the interface name with the firstcapital 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
IEmbeddable,IEnumerable
Interface DeclarationInterfaces 11 C# 30
Interface Declaration An interface can contain methods An interface can contain methods,
properties, indexers and events, none of hi h i l t d i th i t fwhich are implemented in the interface
itself An interface is a reference type that is never directly
created and has no actual representationp Interface method declarations should not be prefixed
with an access modifier They are all, by default, public Interface methods are all, by default, pure virtual , y , p
methods
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Interface DeclarationInterfaces 12 C# 30
Interface DeclarationAn interface can contain also properties An interface can contain also properties, indexers and events The following is an enhanced version of the
IEmbeddable interfaceinterfaceIEmbeddable{{
voidLoad();voidPlay();y();
stringTitle{get;}tCli k dE t Cli k deventClickedEvent Clicked;
stringthis[int index]{get;set;}}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
}
Interface ImplementationInterfaces 13 C# 30
Interface ImplementationA class that is defined to implement an A class that is defined to implement an interface must define all members declared in the interface:
Interface method signatures cannot be modified 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 anThe compiler ensures that an implementing class actually adheres to its i t f t tinterface contract
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Using the Implemented ItemInterfaces 14 C# 30
Using the Implemented Item Instances of a class can be used by the 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();item.Load();
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Inheritance and InterfaceInterfaces 15 C# 30
Inheritance and Interface Consider the following graphical system: Consider the following graphical system:
The shapes class hierarchy is composed of:A b t t b l h d fi i h An abstract base class Shape, defining shapes common fields position and methods Draw(),Resize() and Move()()
Three derived classes : Circle, Rectangle andTriangle, each overrides required methods as well as adding its specific functionalityadding its specific functionality
A Desktop class is defined to manage shapesA Desktop class is defined to manage shapes It contains a list of shapes: List _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
A Graphical System ExampleInterfaces 16 C# 30
A Graphical System Example publicabstractclassShape{//}publicabstractclassShape{//}publicclassCircle:Shape{//}publicclassRectangle:Shape{//}publicclassTriangle:Shape{//}
publicclassDesktop{
privateList shapes=newList;privateList_shapes=newList;publicShapethis[int index]//indexeronshapes{//}{//}publicbool Add(Shapeshape){//}
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
A Graphical System ExampleInterfaces 17 C# 30
Later a new shape behavior was defined
A Graphical System Example 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
publicclassRectangle:Shape IDraw3DShape,IDraw3D
{publicvoidDraw3D()
Shape,IDraw3D{publicvoidDraw3D()
Th f ti lit li d t f th h
publicvoidDraw3D()...}
publicvoidDraw3D()...}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
The new functionality was applied to some of the shape classes without interfering with the overall hierarchy
A Graphical System ExampleInterfaces 18 C# 30
A Graphical System ExampleThe Desktop added a method to enable The Desktop added a method to enable activating the 3D draw: But how should the Draw3D() be defined?
Lets start with a simple attempt:Let s start with a simple attempt:publicbool Draw3D(int index){{
if(index>=_shapes.Count)thrownewIndexOutOfRangeException();
h [i d ] D 3D()_shapes[index].Draw3D()//
}
Can you find any problems with this definition?
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
A Graphical System ExampleInterfaces 19 C# 30
A Graphical System Example The statement shapes[index] Draw3D() The statement _shapes[index].Draw3D()
Gets the following compile error:
Our previous WebPage class stored its items in an'Shape'doesnotcontainadefinitionfor'Draw3D'
Our previous WebPage class, stored its items in an IEmbeddable reference list
ensuring all stored items implement IEmbeddableensuring all stored items implement IEmbeddable
The Desktop class, however, stores its shapes in a more heterogeneous array: a Shape reference listmore heterogeneous array: a Shape reference list
Only Shape class methods can be directly applied on Shapereferencesreferences
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
A Graphical System ExampleInterfaces 20 C# 30
A Graphical System Example Lets cast! 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
Querying for ImplementationInterfaces 21 C# 30
Querying for Implementation The second Draw3D() version would The second Draw3D() version would
compile However, when an index of a shape that does not
implement the IDraw3D interface is provided, a run-time exception I lidC tE ti is throwntime exception InvalidCastException 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 anWe can use the operators is and as to query an
object if it implements a specified interface
ID 3Dth DSh h [i] ID 3DIDraw3DthreeDShape =_shapes[i]asIDraw3D;if(threeDShape !=null)
threeDShape.Draw3D();
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
p ();
Inheritance / Interface RiddleInterfaces 22 C# 30
Inheritance / Interface Riddle The IDra 3D interface presented above The IDraw3D interface presented above
contained a single method named: gDraw3D() What would happen if the interfaces definers would
have called their method merely D ()?have called their method merely Draw()?
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
The Name Collision ProblemInterfaces 23 C# 30
The Name Collision Problem Lets revisit the Circle class definition: Let s revisit the Circle class definition:
publicclassCircle:Shape,IDraw3D{//publicvoidDraw3D(){//}
}
Which Draw() is the Circle class defining?
}
() g The base Shape Draw(), or the IDraw3DDraw()?
Can the class implement both definitionsCan the class implement both definitions of the method only once?
And if so the method has a completely different And if 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
The Name Collision ProblemInterfaces 24 C# 30
The Name Collision Problem In the current Circle class definition: In the current Circle class definition:
the Draw()method will be executed, both when activated in a Circle object (or Shape) context:activated in a Circle object (or Shape) context:Circlecircle =newCircle(5,10,15);circle Draw();
And in a IDraw3D context:circle.Draw();
IDraw3DthreeDShape =_shapes[index]asIDraw3D;if(threeDShape!=null)
threeDShape.Draw();
We would like to be able to define two threeDShape.Draw();
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
Explicit Interface SpecificationInterfaces 25 C# 30
Explicit Interface Specification When implementing an interface method When implementing an interface method
It is possible to explicitly specify the name of the interface to which the method belongs: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
The System InterfacesInterfaces 26 C# 30
The System Interfaces Being a key concept interfaces plays an Being a key concept, interfaces plays an
important role in the .NET framework There are several pre-defined interfaces
The String class, for example, supportsThe String class, for example, supports several members such as:
Concat() Replace()and Length Concat(), Replace()and Length In addition, it implements several interfaces:
publicsealedclassString:IComparable,ICloneable,IConvertible,IComparable,IEnumerable,IComparable,IEnumerable,IEnumerable,IEquatable
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Interfaces: Another ViewpointInterfaces 27 C# 30
Interfaces: Another ViewpointInterfaces pro ide s ith the means for Interfaces provide us with the means for generic programmingg p g g Using interfaces, we can provide general algorithms
as type independent servicesas type independent services
For example, a sort algorithm can be applied to any type, so long as it provides an appropriate comparison methodan appropriate comparison method How will we define this requirement?
Ho ill it be enforced on instances pro ided as How will it be enforced on instances provided as arguments to our algorithm?
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
The IComparable InterfaceInterfaces 28 C# 30
The IComparable InterfaceThe IComparable interface is actually the The IComparable interface is actually the .NET version of the theoretical comparison pinterface idea we have just presented
While learning about the NET array we realized that While learning about the .NET array, we realized that the Array class provides a sorting methodW d it t t h ldi i t We used it to sort an array holding integers
Can this method be called for an array storing any element type?type?
Will it be possible, for example, to sort an array of Employeeobjects?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
The IComparable InterfaceInterfaces 29 C# 30
The IComparable InterfaceTr ing to e ec te the emplo ees program Trying to execute the employees program with the following statements inside:gEmployee[]employees=...;//
Generates this run time exception:
//Array.Sort(employees);
Generates this run time exception:UnhandledException:pSystem.InvalidOperationException:SpecifiedIComparer threwanexception.>S t A tE ti System.ArgumentException:AtleastoneobjectmustimplementIComparable.
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
The IComparable InterfaceInterfaces 30 C# 30
The IComparable Interface IComparable is the interface that is used IComparable is the interface that is used
to compare objects in the sorting methods IComparable contains a single method:
int CompareTo(objectobj );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: This instance is less than obj Zero: This instance is equal to obj Greater than zero: This instance is greater than obj Greater than zero: This instance is greater than obj
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
The IComparable ExampleInterfaces 31 C# 30
The IComparable ExampleclassEmployee:IComparable {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
}
Extension MethodsInterfaces 32 C# 30
Extending an Interface//I S t dll//InSystem.dllpublicinterfaceIComparable {int CompareTo(objectobj);p ( j j);
}//InMyExtensions.dll
M E t i {namespaceMyExtensions {staticclassComparableExtensions {publicstaticbool IsGreater(this IComparable obj,p ( p j,
objectother){returnobj.CompareTo(other)>0;
}}publicstaticbool IsEqual(this IComparable obj,
objectother){j ) {returnobj.CompareTo(other)==0;
}}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
}}//endnamespace
Extending an InterfaceInterfaces 33 C# 30
Extending an Interface//InBigInt.dllclassBigInteger :IComparable {//Implementation
}}
//Inmycode:usingMyExtensions;//Importextensions
BigInt b1=newBigInt(10000000);BigInt b1=newBigInt(10000000);BigInt b2=newBigInt(10000001);
b1.IsEqual(b2);//CompareExtensions.IsEqualb1.IsGreater(b2);//CompareExtensions.IsGreater
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
The IComparable InterfaceInterfaces 34 C# 30
The IComparable Interface We will learn Generics later in this course We will learn Generics later in this course
It is something similar to C++ templates
Using IComparable is expensive in most cases and error pronecases 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 interfaces were introducedg
IComparable is one of them:publicinterfaceIComparablepublicinterfaceIComparable{
int CompareTo(Tother);
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
( )}
Additional Comparing Methods: Interfaces 35 C# 30
The IComparer The IComparable interface is the default 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 criteriaThi b d b d fi i h l l th t i l t This can be done by defining helper classes that implement the IComparer or IComparer interfaces Compare() method
An instance of such a helper class is passed as an additional parameter to the Sort() method
When this is done the provided Compare() method will be When this is done, the provided Compare() method will be used, instead of the default CompareTo() method
This lets us tune the sorting algorithm dynamically
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
g g y y
The IEnumerable InterfaceInterfaces 36 C# 30
The IEnumerable InterfaceC# arra and collections elements can be C# array and collections elements can be iterated using the foreach constructg Is foreach implemented specifically for the
framework collections?framework collections?Or
Does it define a general contract of which any class Does it define a general contract of which any class that adheres to it can join the foreach game?Can we apply the f h statement usage on our Can we apply the foreach statement usage on our user-defined collection class?
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
The IEnumerable InterfaceInterfaces 37 C# 30
The IEnumerable Interface Tr ing to compile the follo ing (some hat Trying to compile the following (somewhat nave) statement on our original ) gEmployeeManager class:foreach (Employeeein_employees)
Console.WriteLine("Name:"+e.Name);
Will generate the following compile error:foreach statementcannotoperateonvariablesoftype'employeeTools.EmployeesManager'becausetype employeeTools.EmployeesManager because'employeeTools.EmployeesManager'doesnotcontainadefinitionfor'GetEnumerator
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
The IEnumerable InterfaceInterfaces 38 C# 30
The IEnumerable Interface It seems that to use the foreach It seems that to use the foreach
statement We should implement the interface: IEnumerable
The IEnumerable interface contains oneThe IEnumerable interface contains one method:IE t G tE t ()
It returns an object of a type that f
IEnumerator GetEnumerator();
implements the IEnumerator interface
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
The IEnumerator InterfaceInterfaces 39 C# 30
The IEnumerator Interface The IEnumerator interface is the actual The IEnumerator interface is the actual
iteration interface, containing the following bmembers:
bj tC t{ t }objectCurrent{get;}bool MoveNext();voidReset();();
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
IEnumerable & IEnumeratorInterfaces 40 C# 30
IEnumerable & IEnumerator It seems that we have two separate It seems that we have two separate
entities: The container class and an enumerator class
The enumerable container does notThe enumerable container does not directly implement the enumeration operations but rather defines a separateoperations, but rather defines a separate enumerator class, as a nested type: This helper class implements the actual enumeration
operations on its containerWh th t i i k d f ti i When the container is asked for enumeration services (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
enumerator class to be used for enumeration
Enumerator ExampleInterfaces 41 C# 30
Enumerator ExampleclassEmployeeManager :IEnumerableclassEmployeeManager :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
Enumerator ExampleInterfaces 42 C# 30
Enumerator Example//Nestedclass//NestedclasspublicclassEnumerator:IEnumerator {publicEnumerator(IList employees){_employees=employees;ResetCurrent();
}publicobjectCurrent{{
get{if( current==1|| current> employees.Count1)(_cu e t || _cu e t > _e p oyees.Cou t )
thrownewInvalidOperationException();return_employees[current];
}}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Enumerator ExampleInterfaces 43 C# 30
Enumerator Examplepublicbool MoveNext(){publicbool MoveNext(){
if(_current
Interfaces and CollectionsInterfaces 45 C# 30
Interfaces and Collections IEnumerable and IComparable are two IEnumerable and IComparable are two
examples of collection-related interfaces The .NET framework provides several collection
classes in System.Collections.Generici d i l List,SortedList,Queue,
Stack,Dictionary and much more All NET collections implement several interfaces that All .NET collections implement several interfaces that
represent basic element management, such as the ICollection &ICollection,IEnumerable &,IEnumerable,ICloneable interfaces
Different collections implement other, more specific interfaces, such as: IList,IList and IDictionary,IDictionary
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
The IFormattable InterfaceInterfaces 46 C# 30
The IFormattable Interface Recall the string formatting discussion 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;l i i (" h h i { }" h )
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Console.WriteLine("Thecharacteris:{0:F}",character);
The IFormattable InterfaceInterfaces 47 C# 30
The IFormattable InterfaceCan I pro ide m sers s ch control o er Can I provide my users such control over the output format printing of my objects?p p g y j Can I enable them produce different output formats
based on provided format characters?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
IFormattable ExampleInterfaces 48 C# 30
IFormattable ExampleclassEmployee:Iformattable {classEmployee:Iformattable {
privateint _id;privatestring name;privatestring_name;privateint _salary;privateint seniority;p ate t _se 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
IFormattable ExampleInterfaces 49 C# 30
IFormattable ExamplepublicstringToString(stringfmt IFormatProvider fp)publicstringToString(stringfmt,IFormatProvider fp){
switch(fmt)switch(fmt){case(null):case ( u ):
returnToString();case"F":
returnString.Format(...);default:
returnToString();}
}}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
IFormattable ExampleInterfaces 50 C# 30
IFormattable ExampleusingSystem;usingSystem;classEmployeesApp {
staticvoidMain(){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 , , yEmployeeno.2:Id:1Name:JaneGender:F
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Seniority:0Salary:12000
Interfaces 51 C# 30
Chapter 12 Exercise 1
THE ENHANCED WEEKLY SCHEDULE EXERCISESCHEDULE EXERCISE
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Chapter SummaryInterfaces 52 C# 30
Chapter SummaryInterfaces define contracts Interfaces define contracts Classes define behavior
Querying a type for an interface implementation can be done with the isimplementation can be done with the isand as operators
Interfaces can be explicitly implemented .NET has many pre-defined interfaces
Many of those interfaces serve as the contractMany 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