-7

I'm using C#. I have a certain number of Newtonsoft.Json.Linq.JArray, let's say A1, A2, A3, and so on. I need to create an array or something similar of this objects in a way that, if I do something on one element of this array, is as doing in to my original objects. Thank you.

struct Product {
    public JArray A1;
    public JArray A2;
    public JArray A3;
    public JArray A4;
};
       
Product  obj=new Product();
       
JArray[] vj=new JArray[4]{obj.A1, obj.A2, obj.A3, obj.A4};

Now, I'm doing:

obj.A1=new JArray(){1,2,3,4,5};
obj.A1.Add("testo");

for every single object.

But I'd like to replace with something like this:

vj[0]=new JArray(){1,2,3,4,5};
vj[0].Add("testo");
vj[1]=new JArray(){3,5,2,3,4};
vj[1].Add("testo");
vj[2]=new JArray(){2,3,4,5,6};
vj[2].Add("testo");
vj[3]=new JArray(){2,2,3,4,5};
vj[3].Add("testo");

but if I do this, the original object, obj.A1 obj.A2 and so on, remain null. So I'm looking for a way to have, let's say, an array of pointers to JArray This is an example. I have a number (that is not fixed) of Ax and the operations that I have to do on every single object is the same. At the end, I'd like to replace the operations that are repetitive, with a for cycle applied to vj. But with this implementation, obj.A1, obj.A2 and so on, are not modified doing vj[i]=.... when I'm in debug, looking to the value of obj.A1 etc. all remain null, so I can't serialize obj at the end of all.

At the end, I have done in the following way and it works.

JArray*[] vj=new JArray*[4]{&obj.A1, &obj.A2, &obj.A3, &obj.A4};
for (i=0;i<4;i++)
{*vj[i]=new JArray(){1,2,3,4,5};
vj[i]->Add("testo");}

so, in the end, I can serialize my Product object. Thank you.

5
  • 6
    Can you please provide some sample code including what you have tried, what happened and desired result. Commented Nov 21 at 9:03
  • 2
    In C#, you have references, not pointers. But for these intents and purposes, it should work similarly. Given that JArray is a reference type, I don't see why that shouldn't work already. Just don't create new objects, use the existing references. Commented Nov 21 at 9:53
  • 6
    Why are you using JArray at all. Work with real objects and use json when you need to serialize Commented Nov 21 at 9:59
  • Think through it: at the point where you create vj, all the references obj.A1 - obj.A4 are null. When you assign a new array to vj[0], how should the runtime know to also assign this to obj.A1? Instead, create the arrays first on the obj, then create your array with the proper references. Then you can modify the values of the four arrays (but not replace them / create new ones). Commented Nov 21 at 10:08
  • 2
    ^^ oooorrrr: share what you are trying to do with this and we can probably come up with something better and working. Commented Nov 21 at 10:59

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.