Game Development Reference
In-Depth Information
3.
Classes and interfaces
One of the following three combined declarations and assignments is correct.
Which one is that, and why are the other two not correct?
List<
int
>a=
new
IList<
int
>();
// version 1
IList<
int
>b=
new
List<
int
>();
// version 2
IList<
int
>c=
new
IList<
int
>();
// version 3
Describe a situation in which the correct version of the above lines of code has
an advantage over the also correct declaration and assignment:
List<
int
>d=
new
List<
int
>();
// version 4
4.
List
and
foreach
Provided is the following class:
class
Counter
{
int
val = 0;
public
Counter(
int
v)
{val=v;
}
public void
Increment()
{
val++;
}
}
and the following instructions in a class that uses the
Counter
class:
List<Counter> list =
new
List<Counter>();
for
(
int
i=0; i<25; i++)
list.Add(
new
Counter(i));
(a) Write a method
Increment
, which gets an
IList<Counter>
object as a parameter
and which increments all the counters (using the
Increment
method in the
Counter
class). Provide a version that uses the
foreach
instruction, as well as
a version that uses a
for
or a
while
instruction.
(b) Suppose that instead of passing a
List<Counter>
object, we would like to pass
an object of type
OwnList<Counter>
, where the
OwnList
class is our own ver-
sion of a list, which implements the
IList
interface. What do we need to
change in the
Increment
method we wrote in the previous question so that
we can use this method with our own list class?
5.
Strings
The
string
class contains (among others) methods that have the following head-
ers: