Let's say I have an array of strings from executing this Split method
string[] parsed = message.Split(' ');
And then I want to store a certain value of this array in a new string
string name = parsed[3];
Now I remove this string from the array using an extension method, this method removes the value at the specified index and shifts everything back to fill the gap
parsed = parsed.RemoveAt(3);
I am aware that because strings are reference types in C# my name variable is now null, after searching a little I've been told that making exact copies of strings in C# is useless. What is the best and correct way to set the name variable as a new instance so that it does not get deleted after the .RemoveAt() call?
EDIT:
This is the best way that I found so far
string name = new string(parsed[3].ToCharArray());
Another way proposed by Willy David Jr
parsed = parsed.Where((source, index) => index != 3).ToArray();
EDIT 2:
Please disregard this question and read the approved answer, I misunderstood how reference types work.
You're misunderstanding how reference types work. Removing an object from an array does not modify that object in any way - it just means that the array no longer contains a reference to the object.
You can test this yourself. Run the code you included in the debugger (or a console app) and then view (or print out) the value of
name
at the end.The thing that can trick you up with reference types occurs when there are two variables (or arrays or whatever) that hold a reference to the same object. In this case, changes made to the object via one variable will be reflected when the object is accessed via another variable - it's the same object, but with two different variables referencing it. If you want both variables to refer to their own "copy" of the object, you have to create a copy yourself and assign it to one of the variables.
However, in C#, the
string
type is immutable, meaning that once astring
object is created there is no way to change that object. So there is never a reason to create a copy of a string. If there is a variable that references a particular string, you can be sure that no other reference can change it out from under you.