C# Exercises / PDF

C# Exercises / PDF











C# Exercises / PDF














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 with properties, operator overloading and user-defined conversions.

A 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) {
this.minutes = 60 * hh + mm;
}
public override String ToString() {
return minutes.ToString();
}
}

Create a VS2005 C# project called TestTime. Modify the Main method to declare variables of type Time,
assign values of type Time to them, and print the Time value using Console.WriteLine. Compile and run
your program.

The next few exercises use this type.

Exercise C# 1.2 In the Time struct type, declare a read-only property Hour returning the number of hours and
a read-only property Minute returning the number of minutes. For instance, new Time(23, 45).Minute
should be 45.

Modify the ToString() method so that it shows a Time in the format hh:mm, for instance 10:05, instead
of 605. You may use String.Format to do the formatting. Use these facilities in your Main method.

Exercise C# 1.3 In 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 value.

It is convenient to also declare an additional constructor Time(int). Use these facilities in your Main method.
For instance, you should be able to do this:

Time t1 = new Time(9,30);
Console.WriteLine(t1 + new Time(1, 15));
Console.WriteLine(t1 - new Time(1, 15));

Exercise C# 1.4 In struct type Time, declare the following conversions:

 an implicit conversion from int (minutes since midnight) to Time
 an explicit conversion from Time to int (minutes since midnight)
Use these facilities in your Main method. For instance, you should be able to do this:
Time t1 = new Time(9,30);
Time t2 = 120; // Two hours
int m1 = (int)t1;
Console.WriteLine("t1={0} and t2={1} and m1={2}", t1, t2, m1);
Time t3 = t1 + 45;
Why is the addition in the initialization of t3 legal? What is the value of........









Download C# Exercises / PDF










C# Exercises / PDF


0 commentaires: