Search code examples
c#arrayssyntaxinitialization

Is there anyway to initialize an array in C# with a repeated value?


I've seen similar questions but the answers are all solutions which must be executed in runtime vs on initialization of the variable. To explain what I'm asking for specifically (and what I'm not asking for) take this example:

Say I have an integer array I want to initialize.

int[] numbers;

Great. But right now it's null. So I'll probably do something like this.

int[] numbers = new int[];

Now it's an empty array of length 0. But I know exactly how long I want this array to be, so instead I do this:

int[] numbers = new int[5];

Now I have an integer array with 5 elements that have all defaulted to the default integer, 0. That's fine, but I actually want this array to initialize with all the elements set to -1. Well I could do this:

int[] numbers = new int[5] {-1,-1,-1,-1,-1};

Cool I have what I want upon initialization....except I actually want the array to have 200 elements....

At this point as far as I've been able to tell my ability to customize the initialized state of this array has reached it's limit. It technically would allow me to manually type out 200 -1's, but obviously I'm not going to do that.

And yes I could use a loop of some kind, the fill method, all those answers in the other questions, but that requires at least one more line of code in an executing block of code. I want to be able to do something like this.

public class MyClass
{
     int[] numbers = new int[] {-1} * 200;
     public Length => numbers.Length;

     public void SetValue(int index, int value)
     {
          if(index >= 0 && index < numbers.Length && numbers[index] != -1)
               numbers[index] = value;
     }
}

Now, it seems clear to me from my research that there simply isn't syntax which allows this. But that is surprising to me. I am hoping that someone has the magic for me. But alternatively, I assume that if something which seems so obviously useful to me can't be done there must be reason for it, and it's probably that it shouldn't be done. If that's the case, this is an opportunity for my understanding of programming to deepen if someone explains why I don't actually want to do this even if I could.

Thanks in advance.


Solution

  • You can use the method Enumerable.Repeat:

    int[] numbers = Enumerable.Repeat(-1, 5).ToArray();
    

    This creates an array containing the element -1 five times.