views:

158

answers:

4

Hi, and thanks for looking.

I have a 2D c# array, that has 50 as one of its dimensions. The other dimension depends on the number of rows in a database somewhere and is decided at runtime. How would I go about initializing an array like this?

Currently my initialization for a single row looks like this, but I'm sure there's a better way to do it, more efficiently :)

temp = new Double[50,1] { {0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},
                                {0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},
                                {0},{0},{0},{0},{0},{0},{0},{0},{0},{0}};
+3  A: 
double[,] temp = new double[50,1];

double[][] temp = new double[50][];

Take a look here for more information about arrays.

Ardman
+4  A: 

Simply initialize the array at runtime using an integer variable for the second dimension.

double[,] = new double[50, v];

C# will automatically initialize all doubles to zero, so in your specific circumstance, you don't need to explicitly initialize the values.

Toby
Thanks for the default initialization tip. I remember trying this and failing, so I posted the question. Must've overlooked something. Anyway, it's working fine now :)
Freakishly
+1  A: 

If a second dim of array can vary use jagged array

double [][] temp = new double [50][]; 

When you will know exact size of array dim you set it with.

temp[index] = new double[length];

If it always has rectangular size use following construct

double [,] temp = new double[50, length];
jethro
That's not a two dimensional array, that's a jagged array. That means that so far it's just an array of 50 null references, you have to create 50 arrays and put in the array. However, spreading the data of a record over 50 separate arrays doesn't seem logical, the outermost array would rather hold rows than columns.
Guffa
+3  A: 

As Toby said, you don't need to explicity set double values to zero since default(double) == 0.0.

However, if you want to initialize all members of an array to some value other than the default for the array's type, you could always do this:

static T[,] GetInitializedArray<T>(int width, int height, T value)
{
    var array = new T[width, height];
    for (int x = 0; x < width; ++x)
    {
        for (int y = 0; y < height; ++y)
        {
            array[x, y] = value;
        }
    }

    return array;
}

This would allow you to write code such as this:

double[,] temp = GetInitializedArray(50, 1, 0.0);
Dan Tao