Search code examples
c#arraysconditional-statementsdeclare

Conditional declaring arrays in two-dimensional char array?


I have a two-dimensional char array declared with four strings.

private static string string1 = "abcde";
private static string string2 = "ABCDE";
private static string string3 = "12345";
private static string string4 = "67890";

public string selectChars(bool includeOne, bool includeTwo, bool includeThree, bool includeFour)
{
   char[][] charGroups = new char[][] 
   {
       string1.ToCharArray(),
       string2.ToCharArray(),
       string3.ToCharArray(),
       string4.ToCharArray()
   };
}

I want to declare and initialize the array such that the string add is conditional based on four bool flags. For example, if includeOne and includeThree are true, I want to end up with a charGroup[2][5] having used string1 and string 3.

(This is existing code where I don't want to radically change the rest of the code. if I can conditionally declare the array in that block, I'm done.)


Solution

  • The manner you want is like a list, so it's better implement it by list and then return an array by ToArray:

    public string selectChars(bool includeOne, bool includeTwo, bool includeThree, bool includeFour)
    {
            List<char[]> chars = new List<char[]>();
            string string1 = "";
            if (includeOne)
                chars.Add(string1.ToCharArray());
            if(includeTwo) ....
    
            char[][] charGroups = chars.ToArray();
    }