Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable length arrays in C#

Tags:

arrays

c#

I have a class which defines few global variables as below:

namespace Algo
{
    public static class AlgorithmParameters
    {
        public int pop_size = 100;

    }
}

In my another csharp file, which also contains the main(), and in the main() I am declaring an array of type structure and the array size as pop_size but I am getting some error on "chromo_typ Population[AlgorithmParameters.pop_size];". Please find the code below. Am I using a incorrect syntax for array declaration of variable length size??

namespace Algo
{
    class Program
    {
        struct chromo_typ
        {
            string   bits;  
            float    fitness;

            chromo_typ() {
                bits = "";
                fitness = 0.0f;
            }

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

        static void Main(string[] args)
        {

            while (true)
            {
                chromo_typ Population[AlgorithmParameters.pop_size];
            }
        }
    }
}

Error is:

Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type.

Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)

Please help.

like image 420
user1277070 Avatar asked Aug 31 '26 20:08

user1277070


2 Answers

You don't specify the size when you declare the variable, you specify it when you create the instance of the array:

chromo_typ[] Population = new chromo_typ[AlgorithmParameters.pop_size];

Or if you separate the declaration and creation:

chromo_typ[] Population;
Population = new chromo_typ[AlgorithmParameters.pop_size];
like image 80
Guffa Avatar answered Sep 02 '26 12:09

Guffa


Change the initialize in this way:

        //while (true) ///??? what is the reason for this infinite loop ???
        //{ 
            chromo_typ[] Population = new chrom_typ[AlgorithmParameters.pop_size] ; 
        //} 

also you need to change pop_size to a static because is declared inside a static class.

like image 34
Steve Avatar answered Sep 02 '26 12:09

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!