What is a convention of passing a list to a constructor and then saving it?

Let's say I have this code:

private IList<Vector3> vertices; private IList<uint> indices; public Mesh(IList<Vector3> vertices, IList<uint> indices) { // ??? } 

To make it clear, I want to keep the vertices and indices inside this constructor. I haven't worked very much with C #, so I'm not sure what the convention looks like. Should I make a copy of the entire list or can I just copy the link? What convention?

+6
source share
5 answers

It depends on the intention. As a rule, you need a separate copy so that you can control the modification of lists inside the function. This is about encapsulation.

If this is not your intention with this class, then this is fine, just to keep links to lists.

+6
source

You can simply copy the link to the list. Since you specified member variables and your constructor arguments with the same name, you need to use the this .

 private IList<Vector3> vertices; private IList<uint> indices; public Mesh(IList<Vector3> vertices, IList<uint> indices) { this.vertices = vertices; this.indices = indices; } 

Now the lists will be saved in your Mesh class.

+4
source

It depends on what you need. You can just write

 this.vertices = vertices; 

This will save the link to the list. This means that every change made outside will be reflected in your list;

Alternatively, you can copy the list -

 this.vertices = new List<Vector3>(vertices); 

This will actually copy the items in the list and you will not see the changes made outside. Note. The copied elements will still be links. Any changes made to them will be reflected inside your method. If you want, you can make a copy of them also for your new list.

Again - it depends on what you need.

+1
source
 private IList<Vector3> vertices; private IList<uint> indices; public Mesh(IList<Vector3> vertices, IList<uint> indices) { this.vertices = vertices; this.indices = indices; } 

If you want to access it in Mesh , then yes, you will need to put them there. This is usually done as described above.

0
source

You should always be careful with such things. For example, if your Mesh class is intended to be immutable, then you should make a copy of the data to prevent any external code from modifying what was intended for invalid data.

Personally, if I have no reason for this, I always keep a copy of the data.

0
source

Source: https://habr.com/ru/post/951332/


All Articles