Question

I have been trying to initialize a structure through an array...

Here's the code:

struct test_struct
{
    double a, b, c, d, e;

    public test_struct(double a, double b, double c, double d, double e)
    {
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
        this.e = e;
    }
};

test_struct[,,] Number = new test_struct[2, 3]
{
    {
        {  12.44, 525.38,  -6.28,  2448.32, 632.04 },
        {-378.05,  48.14, 634.18,   762.48,  83.02 },
        {  64.92,  -7.44,  86.74,  -534.60, 386.73 },
    },
    {
        {  48.02, 120.44,   38.62,  526.82, 1704.62 },
        {  56.85, 105.48,  363.31,  172.62,  128.48 },
        {  906.68, 47.12, -166.07, 4444.26,  408.62 },
    },
};

I cannot use a loop or indexing to do this.. the error that I got is

array initializers can only be used in a variable or field initializer. Try using a new expression instead.

How can this code be corrected?

Was it helpful?

Solution

This code is valid C# and should do what you want:

    struct test_struct
    {
        double a, b, c, d, e;
        public test_struct(double a, double b, double c, double d, double e)
        {
            this.a = a;
            this.b = b;
            this.c = c;
            this.d = d;
            this.e = e;
        }
    };

    private test_struct[,] Number =
    {
        {

            new test_struct(12.44, 525.38, -6.28, 2448.32, 632.04),
            new test_struct(-378.05, 48.14, 634.18, 762.48, 83.02),
            new test_struct(64.92, -7.44, 86.74, -534.60, 386.73),

        },

        {
            new test_struct(48.02, 120.44, 38.62, 526.82, 1704.62),
            new test_struct(56.85, 105.48, 363.31, 172.62, 128.48),
            new test_struct(906.68, 47.12, -166.07, 4444.26, 408.62),
        },
    };

OTHER TIPS

The final solution should be, taken all comments:

private test_struct[,] Number;

public void test()
{
    Number = new test_struct[2, 3]
    {
        {
            new test_struct(  12.44, 525.38,  -6.28,  2448.32, 632.04),
            new test_struct(-378.05,  48.14, 634.18,   762.48,  83.02),
            new test_struct(  64.92,  -7.44,  86.74,  -534.60, 386.73),
        },
        {
            new test_struct(  48.02, 120.44,   38.62,  526.82, 1704.62),
            new test_struct(  56.85, 105.48,  363.31,  172.62,  128.48),
            new test_struct( 906.68, 47.12,  -166.07, 4444.26,  408.62),
        },
    };
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top