Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing reference types(strings) inside methods

Tags:

c#

oop

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?

like image 391
user486371 Avatar asked Nov 30 '10 18:11

user486371


2 Answers

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" !?
}
like image 195
Albin Sunnanbo Avatar answered Oct 07 '22 01:10

Albin Sunnanbo


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)

like image 38
kemiller2002 Avatar answered Oct 07 '22 01:10

kemiller2002