Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the convention for passing in a list to a constructor and then storing it?

Tags:

c#

.net

list

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?

like image 639
Johanna Olofsson Avatar asked Aug 08 '13 15:08

Johanna Olofsson


3 Answers

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.

like image 127
itsme86 Avatar answered Nov 16 '22 15:11

itsme86


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

like image 4
deadboy Avatar answered Nov 16 '22 14:11

deadboy


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.

like image 1
Vadim Avatar answered Nov 16 '22 13:11

Vadim