carlosdelab
carlosdelab

Reputation: 9

C# the object is not created in the class

I have a class called population which is basically a collection of chromosomes. I need to implement a property to get the higher ranked chromosome in the population.

nevertheless, I got the error system out of range. I would like to know what I'm doing wrong. Any clue or idea will be very helpful.

The Class: public class Population<T> : List<T> inherence from List<T> which is the one I used to Add and creates the population class.

public class Population<T> : List<T>
{
    private List<Chromosome> population;
    private int count;

    public Chromosome Higher()
    {
        return population.OrderBy(chr => chr.Fitness).ToList()[population.Count - 1];
    }

    public Population(int sizePopulation)
    {
        count = sizePopulation;
        population = new List<Chromosome>(sizePopulation);
    }
 }

This is how the class is implemented:

   Population<Chromosome> pop = new Population<Chromosome>(sizePop); 

   for (int i = 0; i < sizePop; i++)
            pop.Add(new Chromosome(9, 97, 122));

At some point here, the chromosomes are evaluated and their Fitness properties is defined.

   Chromosome best = pop.Higher(); //get the error out of range.

I should expect a chromosome as a return but I get the

System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index'.

population count is 0.

Upvotes: 0

Views: 125

Answers (1)

Jamiec
Jamiec

Reputation: 136074

You're both inheriting from List and composing your object of a List! Inheriting is probably the wrong thing here, you should be using composition.

You can also make use of Last() to get the final item from the list after ordering.

public class Population
{
    private List<Chromosome> population;

    public Population(int sizePopulation)
    {
        population = new List<Chromosome>(sizePopulation);
    }

    public void Add(Chromosome chromosome)
    {
        population.Add(chromosome);
    }

    public Chromosome Higher()
    {
        return population.OrderBy(chr => chr.Fitness).Last();
    }
 }

And

Population pop = new Population(sizePop); 
for (int i = 0; i < sizePop; i++)
        pop.Add(new Chromosome(9, 97, 122));

Upvotes: 3

Related Questions