Example: stock market

C# Exercises - Aalborg Universitet

C# ExercisesThis note contains a set of C# Exercises originally developed by Peter Sestoft exercise C# purpose of the first four Exercises is to get used to the C# compiler and to get experiencewith properties, operator overloading and user-defined Time value stores a time of day such as 10:05 or 00:45 as the number of minutes since midnight (that is,605 and 45 in these examples). A struct type Time can be declared as follows:public struct Time {private readonly int minutes;public Time(int hh, int mm) { = 60 * hh + mm;}public override String ToString() {return ();}} Create a VS2005 C# project calledTestTime.

C# Exercises This note contains a set of C# exercises originally developed by Peter Sestoft Exercise C# 1.1 The purpose of the first four exercises is to get used to the C# compiler and to get experience

Tags:

  Exercise

Information

Domain:

Source:

Link to this page:

Please notify us if you found a problem with this document:

Other abuse

Advertisement

Transcription of C# Exercises - Aalborg Universitet

1 C# ExercisesThis note contains a set of C# Exercises originally developed by Peter Sestoft exercise C# purpose of the first four Exercises is to get used to the C# compiler and to get experiencewith properties, operator overloading and user-defined Time value stores a time of day such as 10:05 or 00:45 as the number of minutes since midnight (that is,605 and 45 in these examples). A struct type Time can be declared as follows:public struct Time {private readonly int minutes;public Time(int hh, int mm) { = 60 * hh + mm;}public override String ToString() {return ();}} Create a VS2005 C# project calledTestTime.

2 Modify the Mainmethod todeclare variables of type Time,assign values of type Time to them, and print the Time value Compile and runyour next few Exercises use this type. exercise C# the Time struct type, declare a read-only propertyHourreturning the number of hours anda read-only propertyMinutereturning the number of minutes. For instance,new Time(23, 45).Minuteshould be theToString()method so that it shows a Time in the formathh:mm, for instance10:05, insteadof 605. You may do the formatting. Use these facilities in C# the Time struct type, define two overloaded operators: Overload (+) so that it can add two Time values, giving a Time value.

3 Overload (-) so that it can subtract two Time values, giving a Time is convenient to also declare an additional constructorTime(int). Use these facilities in instance, you should be able to do this:Time t1 = new Time(9,30); (t1 + new Time(1, 15)); (t1 - new Time(1, 15)); exercise C# struct type Time, declare the following conversions: an implicit conversion fromint(minutes since midnight) to Time an explicit conversion from Time toint(minutes since midnight)Use these facilities in yourMainmethod. For instance, you should be able to do this:Time t1 = new Time(9,30);Time t2 = 120;// Two hoursint m1 = (int)t1; ("t1={0} and t2={1} and m1={2}", t1, t2, m1);Time t3 = t1 + 45;Why is the addition in the initialization oft3legal?

4 What is the value oft3?ExerciseC# is thisillegal?Why is it legal foraclasstohave a non-staticfieldofthesametypeastheclass?C anyoudeclarea staticfieldnoonoftypeTimeinthestructtype ?Why?ExerciseC# theminutesfieldofstructtypeTimepublic(an dnotreadonly) insteadofprivatereadonly. Thenexecutethiscode:Timet1 = new Time(9,30);Timet2 = t1; 100; ("t1={0}andt2={1}",t1,t2);Whatresultdoyo uget?Why?Whatresultdoyougetif youchangeTimetobea classinsteadofa structtype?Why?ExerciseC# new , declarethisclassthathasa staticmethodSM(), a virtualinstancemethodVIM(), anda non-virtualinstancemethodNIM():classB {publicstaticvoidSM(){ (" ()");}publicvirtualvoidVIM(){ (" ()");}publicvoidNIM(){ (" ()");}}Declarea subclassC ofB thathasa staticmethodSM()thathidesB sSM(), hasa virtualinstancemethodVIMthatoverridesB sVIM, andhasa non-virtualinstancemethodNIM()thathidesB sNIM().

5 Make C s methodsprintsomethingthatdistinguishthem fromB s separateclass(butpossiblyinthesamesource file),writecodethatcallsthestaticmethods ofB ,writecodethatcreatesa singleC objectandassignsit toa variableboftypeB anda variablecoftypeC, () () () (). ()andVIM()andNIM()workasinJava?ExerciseC # toillustratedelegatesand(quiteunrelated, really) , declarea staticmethodPrintIntthathasreturntypevoi dandtakesa singleintargumentthatit variableactoftypeIntActionandassignmetho dPrintInt(asa delegate) (42).Declarea methodstaticvoidPerform(IntActionact,int []arr){ ..}thatappliesthedelegateacttoeveryeleme ntofthearrayarr.

6 UsetheforeachstatementtoimplementmethodP erform. Make anintarrayarrandcallPerform(PrintInt,arr ).ExerciseC# sothatit cantake asargumentanIntActionandany shouldbepossibletocallit like this,forinstance:Perform(PrintInt,2, 3, 5, 7, 11,13, 17);2 Thefirsttwo pagesofexercisesconcerngenerictypesandme thods; # tounderstandthedeclarationofa generictypeinC# genericstructtypebecausestructsaresuitab leforsmallvalue-orienteddata,butdeclarin gagenericclasswouldmake genericstructtypePair<T,U>canbedeclaredasfollows(C#Preciselyexampl e182):publicstructPair<T,U>{publicreadonlyT Fst;publicreadonlyU Snd;publicPair(Tfst,U snd){ fst; snd.}}

7 }publicoverrideStringToString(){return"( "+ Fst+ ", " + Snd+ ")";}}(a)Ina new sourcefile,writea C#programthatincludesthisdeclarationanda lsoa tocheckthattheprogramis well-formed.(b)Declarea variableoftypePair<String,int> andcreatesomevalues,forinstancenewPair<String,int>("Anders", 13), andassignthemtothevariable.(c)Declarea variableoftypePair<String,double>.Createa valuesuchasnewPair<String,double>("Phoenix", )andassignit tothevariable.(d)Canyouassigna valueoftypePair<String,int> toa variableoftypePair<String,double>?Shouldthisbeallowed?(e)Declarea variablegradesoftypePair<String,int>[], createanarrayoflength5 withelementtypePair<String,int> andassignit tothevariable.

8 (ThisshowsthatinC#,theelementtypeofanarr aymaybea typeinstance.)Createa few pairsandstorethemintogrades[0],grades[1] andgrades[2].(f)Usetheforeachstatementto (g)Declarea variableappointmentoftypePair<Pair<int,int>,String>,andcreatea valueofthistypeandassignit Thisshowsthata typeargumentmayitselfbea constructedtype.(h)Declarea methodSwap()inPair<T,U>thatreturnsa new structvalueoftypePair<U,T>inwhichthecomponentshave # oneis to experimentwiththegenericcollectionclasse sofC# t ;.Createa new method,declarea variabletemperaturesoftypeList<double>.(TheC#collectiontypeList<T>is similartoJava s ArrayList<T>).

9 MethodGreaterCountwithsignaturestaticint GreaterCount(List<double>list,doublemin){ .. }thatreturnsthenumberofelementsoflisttha taregreaterthanorequaltomin. Notethatthemethodis notgeneric,butthetypeofoneofitsparameter sis a typeinstanceofthegenerictypeList<T>. # genericmethodwithsignaturestaticint GreaterCount(IEnumerable<double> eble,doublemin){ ..}thatreturnsthenumberofelementsoftheen umerableeblethataregreaterthanorequaltom in. Callthemethodonanarrayoftypedouble[]. Canyoucallit onanarrayoftypeint[]?Now callthemethodontemperatureswhichis a List<double>.If youjustcallGreaterCount(temperatures, )you ll betteroverload(morespecificsignature) callthenew one,youmustcasttemperaturestotypeIEnumer able<double> andthat s legalinC#.

10 InC#it is legal tooverloada GreaterCount(IEnumerable<String> eble,Stringmin){ ..}Thismethodsmusthave a slightlydifferentmethodbody, becausetheoperators(<=) and(>=) ,usemethodCompareTo(..). (..)ineachmethodtobesurewhichoneis # wanttodeclarea methodsimilartoGreaterCountabove, butnowit shouldworkforanenumerablewithany elementtypeT, notjustdouble. ButthenweneedtoknowthatvaluesoftypeT canbecomparedtoeachother. Thereforeweneeda constraintontypeT:staticint GreaterCount<T>(IEnumerable<T>eble,T x) whereT : .. { .. }(Notethatin C#methodscanbeoverloadedalsoonthenumbero ftypeparameters;andthesameholdsforgeneri cclasses,interfacesandstructtypes).


Related search queries