Frankly, in this case, both methods do more or less the same thing. Both will modify the List
that was passed in.
If the objective is to have lists immutable by such a method, the second example should make a copy of the List
that was sent in, and then perform the Add
operation on the new List
and then return that.
I'm not familiar with C# nor .NET, so my guess would be something along the line of:
public List<string> Foo(List<string> list)
{
List<string> newList = (List<string>)list.Clone();
newList.Add("Bar");
return newList;
}
This way, the method which calls the Foo
method will get the newly created List
returned, and the original List
that was passed in would not be touched.
This really is up to the "contract" of your specifications or API, so in cases where List
s can just be modified, I don't see a problem with going with the first approach.