Reputation: 21
Can someone explains the following class declaration. I have been given an assignment to understand a snippet of the code and explain the parts of it. I'm unable to make sense on this class declaration. See if any of you can help.
class AnimalWorld<T> : IAnimalWorld where T : IContinentFactory, new()
{
private IHerbivore _herbivore;
private ICarnivore _carnivore;
private T _factory;
/// <summary>
/// Contructor of Animalworld
/// </summary>
public AnimalWorld()
{
// Create new continent factory
_factory = new T();
// Factory creates carnivores and herbivores
_carnivore = _factory.CreateCarnivore();
_herbivore = _factory.CreateHerbivore();
}
/// <summary>
/// Runs the foodchain, that is, carnivores are eating herbivores.
/// </summary>
public void RunFoodChain()
{
_carnivore.Eat(_herbivore);
}
}
Upvotes: 2
Views: 423
Reputation: 2996
This class represent an animal world. This world is split in continents (which is represented by the T
generic parameter).
When you create a new AnimalWorld
, the class requires that you specify in which Continent you are by provide a class (the T
generic parameter) which has an empty constructor (the new()
constraint) an implements the interface IContinentFactory
(the IContinentFactory
).
Let's take an example : AnimalWorld<Europe> = new AnimalWorld<Europe>()
will work if Europe
is define as follows :
class Europe : IContinentFactory
{
// Don't forget the new() constructor
Europe()
{
//...//
}
// Here IContinentFactory implementation
public IHerbivore CreateHerbivore()
{
//...//
}
// Here IContinentFactory implementation
public ICarnivore CreateCarnivore()
{
//...//
}
}
In addition to that, AnimalWorld<T>
Derive from the interface IAnimalWorld
Upvotes: 0
Reputation: 75306
T : IContinentFactory, new()
More information about new()
:
http://msdn.microsoft.com/en-us/library/sd2w2ew5.aspx
Upvotes: 3
Reputation: 872
First of all, AnimalWorld is a generic class (of T) which should implement the IAnimalWorld interface.
What comes after the "where" keyword are constraints on the T type, saying that T must implement IContintentFactory and have a public constructor that does not require parameters.
Upvotes: 1
Reputation: 5785
It says T must be of type IContinentFactory and must have an empty constructor.
The benefits of that code are:
Upvotes: 1