Let's say I have code like this:
private IList<Vector3> vertices;
private IList<uint> indices;
public Mesh(IList<Vector3> vertices, IList<uint> indices)
{
// ???
}
To make it clear, I want to store the vertices and indices inside it in the constructor. I've not worked very much with C# so I'm not sure how the convention looks. Am I supposed to make a copy of the entire list or can I just copy the reference? What's the convention?
It depends on the intention. Generally though, you'd want a separate copy so you can control modification of the lists inside the function. It's about encapsulation.
If that's not your intent with this class though, then it's perfectly fine to just store references to the lists.
You can just copy the reference to the list.
Since you gave your member variables and your constructor arguments the same name, you'd have to use the this
keyword.
private IList<Vector3> vertices;
private IList<uint> indices;
public Mesh(IList<Vector3> vertices, IList<uint> indices)
{
this.vertices = vertices;
this.indices = indices;
}
The lists will now be stored in your Mesh class
That depends on what you need. You can simply write
this.vertices = vertices;
This will store a reference to the list. This means, every change made outside will reflect in your list;
On the other hand 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 changes made outside. Note - the copied items will still be references. Any changes made to them will reflect inside your method. If you wish, you can make a copy of them as well for your new list.
Again - it depends on what you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With