0

I would like to add a string array to a list of string arrays I have predefined. Here is a minimal working example:

using System;
using System.Collections.Generic;

public class Test
{
    static void Main()
    {
        List<string[]> listOfStringArrays = new List<string[]>();
        listOfStringArrays.Add({"hello", "world"});
    }
}

Unfortunately, the aboce example throws errors like the following:

C:\Users\bm\desktop\temp\csharp_codility\add-string-array-to-list\Program.cs(9,32): error CS1
026: ) expected [C:\Users\bm\desktop\temp\csharp_codility\add-string-array-to-list\console-cu
stom.csproj]
C:\Users\bm\desktop\temp\csharp_codility\add-string-array-to-list\Program.cs(9,32): error CS1
002: ; expected [C:\Users\bm\desktop\temp\csharp_codility\add-string-array-to-list\console-cu
stom.csproj]
002: ; expected [C:\Users\bm\desktop\temp\csharp_codility\add-string-array-to-list\console-cu
stom.csproj]
C:\Users\bm\desktop\temp\csharp_codility\add-string-array-to-list\Program.cs(9,40): error CS1
513: } expected [C:\Users\bm\desktop\temp\csharp_codility\add-string-array-to-list\console-cu
stom.csproj]
C:\Users\bm\desktop\temp\csharp_codility\add-string-array-to-list\Program.cs(9,49): error CS1
002: ; expected [C:\Users\bm\desktop\temp\csharp_codility\add-string-array-to-list\console-cu
stom.csproj]
C:\Users\bm\desktop\temp\csharp_codility\add-string-array-to-list\Program.cs(9,50): error CS1
513: } expected [C:\Users\bm\desktop\temp\csharp_codility\add-string-array-to-list\console-cu
stom.csproj]

The build failed. Fix the build errors and run again.

What is wrong with my code? How can I fix it?

11
  • 2
    Typo: you're missing new [] before the curly brace.listOfStringArrays.Add(new []{"hello", "world"}); Commented Jun 9, 2022 at 14:17
  • You need to use the new keyword in this context: stackoverflow.com/questions/30509177/… Commented Jun 9, 2022 at 14:19
  • In that case I wonder why the docs state that its OK to declare an array explicitly like this learn.microsoft.com/en-us/dotnet/csharp/programming-guide/… Commented Jun 9, 2022 at 14:19
  • 2
    @user32882: It is okay to declare an array explicitly like that. But you're not declaring a variable, you're just passing an argument. The syntax you're trying to use is only valid within a variable declaration. Commented Jun 9, 2022 at 14:26
  • 1
    It's unfortunate that you thought my edit was "annoying" @user32882. I believe it made the actual problem much more clear. Can you explain what was incorrect about it? Commented Jun 9, 2022 at 14:30

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.