Reputation: 4104
I've got this method that is passed an array of files. It then replaces any /
with \\
. Then I call a method and pass the array to it, which puts the argument into a new array, formats the itand returns the new array. Next, I call the same method again, pass it the same local array, format it differently, and out
both arrays. Problem is, the second method call is retaining the format from the first method call.
public void Verify(string[] svnFiles, out string[] local, out string[] build)
{
//replace / with double \\
var transformed = TransformToFolders(svnFiles);
build = GetFiles(_buildPath, transformed);
local = GetFiles(_localPath, transformed);
}
private static string[] GetFiles(string path, params string[] files)
{
var moddedFiles = files;
for (var i = 0; i < files.Count(); i++)
moddedFiles[i] = string.Format(@"{0}\{1}", path, moddedFiles[i]);
return moddedFiles;
}
So when I call local = GetFiles(_localPath, transformed);
transformed
has the same values as moddedFiles
. GetFiles
used to manipulate its files
parameter directly and I was getting the same behavior, so that's why I tried creating a new array, but moddedFiles
seems to still just be a reference instead of an actual copy. Is there an easy way to make an actual copy of it so that way I'm not getting basically _localPath\_buildPath\moddedFile
?
Upvotes: 0
Views: 65
Reputation: 1504172
It sounds like you want:
var moddedFiles = (string[]) files.Clone();
That will create a shallow copy of the array, which is largely equivalent to a deep copy when it comes to strings, as they're immutable.
However, a cleaner (IMO) alternative would be to use LINQ:
private static string[] GetFiles(string path, params string[] files)
{
return files.Select(file => string.Format(@"{0}\{1}", path, file))
.ToArray();
}
Or if you really want to keep your original rough approach, you don't need to clone the array really - just create a new array of the right size.
private static string[] GetFiles(string path, params string[] files)
{
var moddedFiles = new string[files.Length];
for (var i = 0; i < files.Length; i++)
{
moddedFiles[i] = string.Format(@"{0}\{1}", path, files[i]);
}
return moddedFiles;
}
Upvotes: 4