Search code examples
c#arraysjsonindexoutofrangeexception

How to append an element to a C# array for JSON reasons?


I'm still working on my JSON parser and writer.

Using Visual Studio Web Essentials, I have created a class diagram, which contains some arrays where I can put information, like this one:

public Channel[] channels { get; set; }

As you see, this is an array without predefined size (a dynamical one), and now I'd like to add something to this array, but this seems not that simple: this post, called "Adding values to a C# Array" mentions how to do this:

  • There are plenty of solutions in case the array size is known (which is not my case).
  • Use an intermediate container (a List) .... Sorry, I'd like to avoid copying my data back and forth, it looks like a performance nightmare.
  • Use the Add() method. I don't have an Add() method.
  • Use the Resize() method. I don't have a Resize() method.
  • Using using System.Linq;, methods like Append() become available. Sorry, but that using clause is present, but I don't have an Append() method.
  • Do some Enumarable...ToArray(): this also looks like copying data back and forth, just looking like another performance nightmare.

I can't believe that Web Essentials decided to use dynamical arrays without having a simple method in mind to manipulate those arrays. Does anybody have an idea?

Hereby an excerpt of my source code, throwing an IndexOutOfRangeException:

root.<stuff>.channels[root.<stuff>.channels.Length] = new Channel();

I checked the IsFixedSize attribute: it is true and read-only.

Oh, I'm working with Visual Studio Enterprise 2019, my .Net target framework seems to be 4.6.1, which seems to be the highest version, installed on my PC.

Thanks in advance


Solution

  • You can't resize fixed size array. The array is always has a fixed size

    The best solution here is to use List<Channel> instead of Channel[].

    Otherwise you can create a new array with the size of the previous plus one and set adding value by the last array index, but my opinion that it would be dirty.

    Here are msdn docs about arrays: Array Here is what the say

    Unlike the classes in the System.Collections namespaces, Array has a fixed capacity. To increase the capacity, you must create a new Array object with the required capacity, copy the elements from the old Array object to the new one, and delete the old Array.