Search code examples
c#arraysrepeat

How to declare the same string value multiple times inside an array?


My question is in relation to multiple array values that are the same within C#. As a rosary has five decades, I want to make values "arr[1,2,...10, 14,16,...23]="Hail Mary";" I could just write each value out in the string array, but feel reducing the size of code would make the program more efficient in limiting its size. Most questions that deal with repetitious values tend to be asked to avoid such, but this deals with different circumstances and a different type such as int. Mine is just the opposite where I am using string and desire to repeat the same value in multiple index numbers. I think there can be multiple uses such as a windows form program that repeats step-by-step instructions to a user to follow that might display a repeated string value.

1)is there a way to code an array with multiple same values, or do I just write each value out as my example already does?

2)If using string[] arr={"Our Father", "Hail Mary", "Hail Mary",..., "Glory Be", "O My Jesus"}; instead of my example that declares each indexed string value, how would it be coded to insert the same value inside the declared string array?

int counter=0;

private void button1_Click(Object sender, EventArgs e)
    {  string[] arr= new string[12]; 
arr[0]="Our Father...";
arr[1]="Hail Mary...";
arr[2]="Hail Mary...";
...
arr[11]="Glory Be...";
arr[12]="O My Jesus...";

textBox1.Text = arr[counter];
counter++;
textBox1.Text = arr[counter-1].ToString();
}

Solution

  • You can use switch statement for such purpose:

    string[] arr= new string[23];
    for (int i = 0; i < arr.Length; i++) {
        switch (i) {
        case 0:
            array[i] = "Our Father...";
            break;
        case 11:
            arr[11]="Glory Be...";
            break;
        case 11:
            arr[12]="O My Jesus...";
            break;
        default:
            array[i] = "Hail Mary";
            break;
        }
    }
    

    The sense is that the most common entry would be "Hail Mary", you put it as a default case and process the rest of the cases separately.

    Note also I'm using arr.Length instead of just number; I'd recommend you to always do that as a good practice (to not repeat same constants over and over).