c# - Should I be reusing collections passed as parameters -


yesterday spent time trying find bug. long story short, realized because of constructor:

public triangle(list<vertex> vertices) {     this._values = vertices; } 

i tried initialize object list of values , object took reference object instead of getting values list. if don't abandon list passed parameter , use later else initializing else same values or if decide clear , fill new values, destroy state of triangle object without knowing it.

my first reaction "fix bug" in constructor started thinking if it's way should be. what's practice covers things that? in general, should think constructors/init methods take list of values? should leave intact? allowed reuse list , fault when leads error?

i mean, can that:

var triangle = new triangle(new list<vertex>(vertices)); 

but shouldn't done creators of triangle class already?

i know guidelines on that. thanks.

personally agree henk; should create copy.

    /// <summary>     /// initialises new instance of <see cref="triangle"/> class      /// contains elements copied specified collection.     /// </summary>     /// <param name="vertices">     /// collection of vertices elements copied.     /// </param>     public triangle(ienumerable<vertex> vertices)     {         this.vertices = new list<vertex>(vertices);     } 

whatever choose make sure document consumers know behaviour expect.

therefore consumers know can safely call new triangle(vertices).


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -