Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A constant value is expected when initialize an array

Tags:

c#

I developing an image processing software.

int size = 3;

int[,] kernel = new int[size, size] {
        {1, 2, 1},
        {2, 4, 2},
        {1, 2, 1}
};

When I compile my code, I have a compile error message "A constant value is expected" from size variable. I understand I can put 3 on my kernel array initialization or make my size constant. What I ask is the technical reason behind this error because this error don't make any sense for me.

like image 687
Khairuddin Ni'am Avatar asked Aug 29 '10 10:08

Khairuddin Ni'am


2 Answers

You can either create an array with empty values by specifying only the size (which may be variable), or list the values in an initializer and optionally specify a constant size. But you can't combine an initializer with a non-constant size. In the case of the initializer you're allowed to specify constant values for the size, if you want to make sure that the initializer results in an array of a specific size.

Just get rid of the size parameters, your initializer list already specifies the size.

like image 155
Matti Virkkunen Avatar answered Sep 30 '22 00:09

Matti Virkkunen


The compiler requires a constant expression for the array ranks. You can declare size as const int, or you can just let the compiler figure it out from the initialization expression:

    int[,] kernel = new int[,] {
            {1, 2, 1},
            {2, 4, 2},
            {1, 2, 1}
    };
like image 22
Chris Schmich Avatar answered Sep 30 '22 01:09

Chris Schmich