0

Lets say I have an array of employee wages in the order of average, max, and min:

int[] wages = {0, 0, Int32.MaxValue};

The above code is initalized so that as Im finding the max I can do a comparison to 0 and anything above the existing value will beat it and replace it. So 0 works fine here. Looking at the min, if I were to set that to 0 I'd have a problem. Comparing wages (all greater than 0) and replacing the minimum with the lowest wage will be impossible because none of the wages would be below the 0 value. So Instead I've used Int32.MaxValue because It's guaranteed every wage will be below this value.

This is just one example but there are others where it would be convenient to reset and array back to its initialized contents. Is there syntax for this in c#?

EDIT: @Shannon Holsinger found an answer with: wages = new int[] {0, 0, Int32.MaxValue};

Capn Jack
  • 1,201
  • 11
  • 28

1 Answers1

0

Short answer is that there's not a built-in way of doing this. The framework doesn't automatically keep track of your array's initial state for you, just its current state, so it has no way of knowing how to re-initialize it to its original state. You could do it manually though. The exact approach to this depends on what your array was initialized to in the first place:

        // Array will obviously contain {1, 2, 3}
        int[] someRandomArray = { 1, 2, 3 };

        // Won't compile
        someRandomArray = { 1, 2, 3 };

        // We can build a completely new array with the initial values
        someRandomArray = new int[] { 1, 2, 3 };

        // We could also write a generic extension method to restore everything to its default value
        someRandomArray.ResetArray();

        // Will be an array of length 3 where all values are 0 (the default value for the int type)
        someRandomArray = new int[3];

The ResetArray extension method is below:

// The <T> is to make T a generic type
public static void ResetArray<T>(this T[] array)
    {
        for (int i = 0; i < array.Length; i++)
        {
            // default(T) will return the default value for whatever type T is
            // For example, if T is an int, default(T) would return 0
            array[i] = default(T);
        }
    }