1
namespace Test { class Program { static void Main(string[] args) { A a = new A(); a.MyString = "Metallica "; PrintA(a); Console.WriteLine(a.MyString); string name = "Linkin "; Print(name); Console.WriteLine(name); Console.ReadLine(); } static void PrintA(A a) { a.MyString = a.MyString + "Rocks"; Console.WriteLine(a.MyString); } static void Print(string text) { text = text + "Park"; Console.WriteLine(text); } } class A { public string MyString { get; set; } } } 

Output:

Metallica Rocks

Metallica Rocks

Linkin Park

Linkin

My question here is that, if string is a reference type (i.e. a class) then why does it not change value of the variable name after the method Print() is called, like it happens for reference variable a's member MyString.

1
  • 2
    "reference type" does not mean that it would be passed by reference. Commented Dec 5, 2015 at 18:56

1 Answer 1

0

In .NET, String is a reference type. It is passed by reference. However, when you make a change to the string value, another new copy is created of it leaving the original one unchanged. This is why it acts as if it is being sent by value

Sign up to request clarification or add additional context in comments.

2 Comments

No. Pass by value vs pass by reference and value type vs reference types are completely different subjects. They are not related.
This answer is wrong. Strings are a reference type, but he reference is passed by value. It also is not copied when you make a change, but instead a new string is created and assigned to the reference; because the reference was passed by value the change is not reflected to the caller.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.