-3

I'm confused by the following. If string is a reference type in C# and gets passed as a reference type, why doesn't changing the parameter value inside the method lead to change of value in the original argument?

Surely, value at which the reference 'z' points to has been changed to "Mike" in the method?

    public static void ChangeStudentName(string param)
    {
        param = "Mike";
    }

    string z = "Bill";
    ChangeStudentName(z);
    Console.WriteLine(z);


Output - Bill
eashan
  • 57
  • 8
  • 3
    `Surely, value at which the reference 'z' points to has been changed` - no, it hasn't. See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref. There is nothing specific to `string` here. – GSerg Aug 29 '20 at 16:33
  • 2
    The reference is passed by value, just as with all reference types. Changing the value of the parameter doesn't change the value of the argument. Please read https://jonskeet.uk/csharp/parameters.html really carefully. – Jon Skeet Aug 29 '20 at 16:35
  • 1
    Does this answer your question? [string is reference type but why it work as a value type when it's assignment updated](https://stackoverflow.com/questions/36276619/string-is-reference-type-but-why-it-work-as-a-value-type-when-its-assignment-up) – Afshin Aug 29 '20 at 16:36
  • None of the answers, unfortunately, answer your question--including the duplicate. Tbh the duplicate has very poor answers. However, there is some useful information in [this thread](https://stackoverflow.com/questions/636932/in-c-why-is-string-a-reference-type-that-behaves-like-a-value-type#:~:text=A%20String%20is%20a%20reference,they%20reference%20the%20same%20object.) – CodingYoshi Aug 29 '20 at 18:07

1 Answers1

3

You want ChangeStudentName(ref string param). Please see the explanation ref (C# Reference). From the article:

Do not confuse the concept of passing by reference with the concept of reference types. The two concepts are not the same. A method parameter can be modified by ref regardless of whether it is a value type or a reference type. There is no boxing of a value type when it is passed by reference.

Rich
  • 261
  • 1
  • 7
  • This does not answer the question but simply talks about another topic. The other topic is related but nonetheless does not answer the question. – CodingYoshi Aug 29 '20 at 18:10
  • @CodingYoshi This answers the question precisely. The OP has confused the concept of passing by reference with the concept of reference types. – GSerg Aug 29 '20 at 18:55
  • No the OP is not confused but asking why a string, which is a reference type, behaves like a value type. – CodingYoshi Aug 29 '20 at 20:18
  • @CodingYoshi No, the OP is asking why a string, which is a reference type, does not behave like it's passed by reference. Its value is being changed inside the method, but the change is not visible outside the method. – GSerg Aug 29 '20 at 20:52