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.

Afaq
  • 1,146
  • 1
  • 13
  • 25

1 Answers1

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

yazan_ati
  • 263
  • 3
  • 3
  • 8
    No. Pass by value vs pass by reference and value type vs reference types are completely different subjects. They are not related. – Soner Gönül Dec 05 '15 at 19:01
  • 6
    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. – Greg Beech Dec 06 '15 at 10:09