Game Development Reference
In-Depth Information
12.5 The
IList
Interface
It is possible that in the future, someone will write a class that has exactly the same
methods as
List
, but it offers some advantages: the methods are faster, or the objects
take up less space in memory (or even both, but that is a lot to ask). Let us say that
in a few years a new class
FastList
becomes available. Because it is so much better,
we want to change our
SnowFlakes
program to take advantage of this new class.
That is not a problem. We have to change the declaration of the member variable
snowflakes
:
FastList<Snowflake> snowflakes;
and in the constructor, we modify the initialization to:
snowflakes =
new
FastList<Snowflake>();
The rest of the program can stay as it is, if the
FastList
class offers exactly the same
methods as
List
.
However, generally it is not so easy to change the program. For example, if the
list is passed as a parameter to methods, we also need to change the declarations
of the parameters in these methods. Then we also have to make sure that when the
methods are called, the parameter is indeed a
FastList
object instead of a
List
object.
This can be a lot of trouble.
One way to avoid this problem is to try and predict the future. When we declare
the member variables and the parameters, we will not say that we are going to use
a
List
or a
FastList
(because the latter does not exist yet). Instead, we declare our
variables of type
IList
.The
IList
type is not a class, but an
interface
. An interface is
a specification of which methods and properties objects of that type should have,
without already implementing these methods and properties. Therefore, it is not
possible to make an instance of an interface-type, because the interface does not
specify what the objects look like, only what they should be capable of doing. When
we initialize a variable of an interface-type, this means we have to make a choice,
for example:
IList<Snowflake> snowflakes;
snowflakes =
new
List<Snowflake>();
When a new, better version of the
List
class becomes available, we can leave the
declaration as is, and we only have to change the initialization. As you can see
in this example, we can assign an object of type
List
to the member variable of
type
IList
. This is possible because the
List
class promises in its header that it is
an
implementation
of the interface
IList
. In other words: all the methods that were
promised in the interface, exist in the
List
class. And the compiler verifies this.