Search code examples
c#stringallocation

C# new string[2] vs new string[]


Is there a difference between the following In terms of performance?

private static readonly string[][]  a = { new string[] {"a", "b", "c"}};
private static readonly string[][]  a = { new string[3] {"a", "b", "c"}};

Assuming I can write the 2 options (I know the values that will be in the array beforehand) which is better / more correct?


Solution

  • Both generates the same IL codes, so same performance, and both are correct.

    The only advantage of the second option is when you need to restric the number of elements, it will give you a compile error if you put more or less elements.

    // error
    private static readonly string[][] a = { new string[3] {"a", "b"}};