Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic initialization of multidimensional array

I have a multidimensional array, which I want to initialize in a simple and fast way:

double[,,] arr = new double[4,5,6];
// doesn't work by design
foreach(double d in arr)
   d = ... ; // my initialization value

This obviously doesn't works. But I would like to have a generic function for setting all array values to a choosen default. With own classes, I could write a special constructor, but with value types I've no real idea. With C++, I could access all items in a linear way with one for loop, but in C# I think I've to use as much for loops as I have dimensions. I've no better solution at the moment ( or I'm using unsafe code and pointer arithmetics, which would probably work.).

Is there a more elegant way for doing this ?

like image 449
Florian Storck Avatar asked Feb 25 '26 11:02

Florian Storck


1 Answers

Not quite sure if it's what you want, but the following extension method will allow you to initialise every value in an array, regardless of the number of dimensions.

public static class ArrayExtensions
    {
        public static void Set<T>(this Array array, T defaultValue)
        {
            int[] indicies = new int[array.Rank];

            SetDimension<T>(array, indicies, 0, defaultValue);
        }

        private static void SetDimension<T>(Array array, int[] indicies, int dimension, T defaultValue)
        {
            for (int i = 0; i <= array.GetUpperBound(dimension); i++)
            {
                indicies[dimension] = i;

                if (dimension < array.Rank - 1)
                    SetDimension<T>(array, indicies, dimension + 1, defaultValue);
                else
                    array.SetValue(defaultValue, indicies);
            }
        }
    }

Use like so:

int[, ,] test1 = new int[3, 4, 5];
test1.Set(1);

int[,] test2 = new int[3, 4];
test2.Set(1);

int[] test3 = new int[3];
test3.Set(1);
like image 190
Andy Holt Avatar answered Feb 27 '26 01:02

Andy Holt



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!