user1277070
user1277070

Reputation: 785

Structures in C#

I am using a structure in my program as below:

public struct chromo_typ
{
        public string   bits;  
        public float    fitness;

        chromo_typ(string bts, float ftns)
        {
            bits = bts;
            fitness = ftns;
        }
};

I am using the constructor defined in the struct i.e. chromo_typ(string bts, float ftns) in my main(). My main() contains the following code:

chromo_typ[] temp = new chromo_typ[VM_Placement.AlgorithmParameters.pop_size];

                    chromo_typ ct = new chromo_typ();

                    int cPop = 0;

                    //loop until we have created POP_SIZE new chromosomes
                    while (cPop < VM_Placement.AlgorithmParameters.pop_size)
                    {
                        // we are going to create the new population by grabbing members of the old population
                        // two at a time via roulette wheel selection.
                        string offspring1 = p.Roulette(TotalFitness, Population);
                        string offspring2 = p.Roulette(TotalFitness, Population);

                        //add crossover dependent on the crossover rate
                        p.Crossover(offspring1, offspring2);

                        //now mutate dependent on the mutation rate
                        p.Mutate(offspring1);
                        p.Mutate(offspring2);

                        //add these offspring to the new population. (assigning zero as their
                        //fitness scores)
                        temp[cPop++] = ct.chromo_typ(offspring1, 0.0f);
                        temp[cPop++] = ct.chromo_typ(offspring2, 0.0f);

                    }//end loop

I am getting the following error at temp[cPop++] = ct.chromo_typ(offspring1, 0.0f); and temp[cPop++] = ct.chromo_typ(offspring2, 0.0f);

Error: 'VM_Placement.Program.chromo_typ' does not contain a definition for 'chromo_typ' and no extension method 'chromo_typ' accepting a first argument of type 'VM_Placement.Program.chromo_typ' could be found (are you missing a using directive or an assembly reference?)

Am I using structure incorrectly? How can I resolve this?

Upvotes: 1

Views: 272

Answers (1)

Ed Swangren
Ed Swangren

Reputation: 124790

In this case, chromo_typ is a constructor, but you are calling it as an instance method. Constructors are used to construct an object, i.e.,

temp[cPop++] = new chromo_typ(arg1, arg2);

It is not a method that you can call on an instance of your type.

On a side note, the canonical way to name types in C# is to use start with an uppercase letter and use camel case, i.e.,

public struct ChromoTyp { }

Of course, this is not a rule, but it is usually a good idea to follow the patterns already in use by the community.

Upvotes: 5

Related Questions