Bert Ernie
Bert Ernie

Reputation: 33

Returning a new value

I have write a function but this function still returns me the old string in stead of the new one. I don't know how to return a new string when you did something with the old one

By example:

public string TestCode(string testString)
{

// Here something happens with the testString


//return testString; <-- i am returning still the same how can i return the new string //where something is happened with in the function above

}

Upvotes: 1

Views: 53

Answers (3)

String is immutable (i.e. cant be changed). You have to do like this

      myString = TestCode(myString) 

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1064324

Simply make sure you assign the new string value to a variable (or the parameter testString). For example, a very common mistake here is:

testString.Replace("a", ""); // remove the "a"s

This should be:

return testString.Replace("a", ""); // remove the "a"s

or

testString = testString.Replace("a", ""); // remove the "a"s
...
return testString;

The point is: string is immutable: Replace etc do not change the old string: they create a new one that you need to store somewhere.

Upvotes: 0

Habib
Habib

Reputation: 223422

// Here something happens with the testString

Make sure what ever you are doing with the string, you are assigning it back to testString like.

testString = testString.Replace("A","B");

since string are immutable.

I assume you are calling the function like:

string somestring = "ABC";
somestring = TestCode(somestring);

Upvotes: 5

Related Questions