0

Below is my code:

string str = ""

double totalCost = getCost(12.5. 20.2, str);

console.WriteLine(str)   // print nothing here

and the getCost function is

double getCost(double inputA, double inputB, string nameofType) {

   if(...){
     nameofType = "xxx";
   } else if (...) {
     nameofType = "xxx";
   } else {
     nameofType = "xxx";
   }
}

I know string get passed in functions, so inside getCost function, one condition is always met, so the string will point to the new value, so why when I use Console.WriteLine to check the string str was still "", looks like it hasn't been changed?

  • 6
    Does this answer your question? [C# string reference type?](https://stackoverflow.com/questions/1096449/c-sharp-string-reference-type) – A Friend Dec 06 '19 at 14:36
  • You are basically doing: `string str = ""; string nameofType = str; nameofType = "xxx";` so of course the original `str` isn't changed. That's not exclusive to `string` variables. Imagine having `List list = new List {1,2,3};` and a method `void WontActuallyChangeTheList(List input) { input = new List {4,5,6}; }` and calling that method with the previously declared `list`. The value `list` is refering to, won't be changed. With `=` you change, what the _variable_ is referencing. You don't actually change the referenced _value_. – Corak Dec 06 '19 at 14:51
  • If instead inside the method you'd do something like `input.Add(9);`, then you would actually change the _value_ and because the _variable_ `list` references the same _value_, you can see the changes there, too. Now a `string` is immutable, so you cannot change the _value_, so you can't do anything in the method, that would change what the outside _variable_ `str` is refering to. If you want to do _that_, you need to use the [ref keyword](https://learn.microsoft.com/dotnet/csharp/language-reference/keywords/ref) (the same as if you would want to change, what `list` is refering to). – Corak Dec 06 '19 at 14:59

0 Answers0