Faraz Shahid
Faraz Shahid

Reputation: 21

c# Generics Class definition explanation

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

Answers (4)

Nicolas Voron
Nicolas Voron

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

cuongle
cuongle

Reputation: 75306

T : IContinentFactory, new()

  1. T must inherit from IContinentFactory
  2. T must have parameterless constructor.

More information about new(): http://msdn.microsoft.com/en-us/library/sd2w2ew5.aspx

Upvotes: 3

strmstn
strmstn

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

dwonisch
dwonisch

Reputation: 5785

It says T must be of type IContinentFactory and must have an empty constructor.

The benefits of that code are:

  • new(): You can access the constructor and instantiate a new T inside your class.
  • IContinentFactory: You can access all elements declared in that interface when using your object of T.

Upvotes: 1

Related Questions