Changing reference types(strings) inside methods

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?

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" !?
}

Need Your Help

jQueryTOOLS Overlay lightbox not functioning when HTML/LINK is loaded via ajax

javascript jquery ajax overlay jquery-tools

Before starting, I have researched and found this similar, previous question: Reinitialize jQuerytools Overlay on ajax loaded element

How to set tooltip at runtime in MFC Treeview?

c++ mfc

How to set tooltip at runtime in MFC Treeview ?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.