Example: bankruptcy

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. 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.

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. 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.

2 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. 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.

3 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? 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().

4 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. 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;}publicoverrideStringToString(){retu rn"("+ Fst+ ", " + Snd+ ")";}}(a)Ina new sourcefile,writea C#programthatincludesthisdeclarationanda lsoa tocheckthattheprogramis well-formed.

5 (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.(ThisshowsthatinC#,theelem enttypeofanarraymaybea typeinstance.)Createa few pairsandstorethemintogrades[0],grades[1] andgrades[2].(f)Usetheforeachstatementto (g)Declarea variableappointmentoftypePair<Pair<int,int>,String>,andcreatea valueofthistypeandassignit Thisshowsthata typeargumentmayitselfbea constructedtype.

6 (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>). 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[].

7 Canyoucallit onanarrayoftypeint[]?Now callthemethodontemperatureswhichis a List<double>.If youjustcallGreaterCount(temperatures, )you ll betteroverload(morespecificsignature) callthenew one,youmustcasttemperaturestotypeIEnumer able<double> andthat s legalinC#.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.

8 { .. }(Notethatin C#methodscanbeoverloadedalsoonthenumbero ftypeparameters;andthesameholdsforgeneri cclasses,interfacesandstructtypes).Compl etethetypeconstraintandthemethodbody. TrythemethodonyourList<double> andonvariousarraytypessuchasint[]andStri ng[]. ThisshouldworkbecausewheneverT is a simpletypeorString,T implementsIComparable<T>.ExerciseC# genericdelegatetypeAc-tion<T>thathasreturntypevoidandtakesasargumenta T a generalizationofyesterday s classthathasa methodstaticvoidPerform<T>(Action<T>act,paramsT[]arr){ ..}Thismethodshouldapplythedelegateactto everyelementofthearrayarr. Usetheforeachstatementwhenimplementingme thodPerform<T>.ExerciseC# (Optional)Asyouknow, C#doesnothave , ,inthecaseoftheGreaterCount<T>(IEnumerable<T> eble,T x)method,it is notreallynecessarytorequirethatT implementsIComparable<T>.

9 It sufficesthatthereis a supertypeUofT suchthatUimplementsIComparable<U>.Thiswouldbeexpressedwitha wildcardtypeinJava, butinC# canbeexpressedlike this:staticint GreaterCount<T,U>(IEnumerable<T> eble,T x)whereT : UwhereU : IComparable<U>{ ..}Whenyoucallthismethod,youmayfindthatt heC#compiler s typeinferencesometimescannotfigureoutthe typeargumentstoa thetypeargumentsexplicitlyinthemethodsca ll,likethis:intcount= GreaterCount<Car,Vehicle>(carList, car);ExerciseC# toillustratetheuseandeffectofa (seeC#Preciselysection28)maybeputonclass es,methods,andsoonthatshouldnotbeused it correspondstothe deprecated warningssowellknownfromtheJava classcontaininga methodstaticvoidAcousticModem(){ ("beepbuupbaapbzfttfsst%^@ toshow how todeclarea new attribute,how toputit onvarioustargets,andhow todetectat run-timewhatattributeshave beenputofa giventarget(inthiscase,a method).)}

10 Createa new customattributeBugFixedthatcanbeusedoncl assdeclarations, mustbelegal constructorsintheattributeclass:onetakin gbotha bugreportnumber(anint) anda bugdescription(astring),andanotheronetak ingonlya description.(Presumablythelatteris usedwhena bugdoesnotgetreportedthroughtheofficialc hannels).Whennobugnumberis givenexplicitly, thenumber 1(minusone)is aToString()methodthatshowsthebugnumberan ddescriptionif thebugnumberis positive, shouldbelegal tousetheBugFixedattributelike this:classExample{[BugFixed(4,"Performan ce:UsesSortedDictionary")][BugFixed(3,"T hrowsIndexOfOutRangeExceptionon emptyarray")][BugFixed("Performance:Uses repeatedstringconcatenationin for-loop")][BugFixed(2,"Loopsforeveron one-elementarray")][BugFixed(1,"Spelling mistakesin output")]publicstaticStringPrintMedian(i nt[]xs){/*.}}


Related search queries