I am passing a string variable to a method. I know strings are reference types but the value that I assign inside the method is lost.
public static void TestMethod(string myString)
{
myString = "world";
}
static void Main(string[] args)
{
string s = "hello";
Console.WriteLine(s); // output is "hello"
TestMethod(s);
Console.WriteLine(s); // output is also "hello" not "world" !?
}
Anyway this does not happen with an array for example. Can someone explain why might be the cause?
Because myString = "world"
assigns a new string to the parameter, not updating the existing string. To update the original reference to the string you must pass the parameter with ref
.
public static void TestMethod(ref string myString)
{
myString = "world";
}
static void Main(string[] args)
{
string s = "hello";
Console.WriteLine(s); // output is "hello"
TestMethod(ref s);
Console.WriteLine(s); // output is also "hello" not "world" !?
}
Yes, because without a ref (or out) you can't assign a new object to a parameter. Since you didn't pass it in through a ref, the variable outside the method still references the original string which didn't change. Consequently, strings are immutable, so you can't do anything to it without create a new string once it is instantiated.
The array can be altered (or the contents of the array can be altered), because the references inside the array are not immutable (you can say reassign my_object1 to equal "BLAH"). You can replace a value in the array and have it accessible outside of the array, because the reference to the array outside of the method hasn't changed.
Link to String in MSDN (talks about immutability)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With