2

So I'm obviously fairly new to programming, but am trying to figure out why this isn't working

I'm trying to take the string myname, and add Mr. to the start of it. I know I could do it simply as just myname = "Mr. " + myname however I'm trying to understand how to use methods to change the values of variables. So, why doesn't this change?

public class Program { public static void Main(string[] args) { string myname = "harry"; Console.WriteLine(myname); //output is harry namechanger(myname); //this should modify harry to Mr. Harry Console.WriteLine(myname); //output is still harry? } static string namechanger(string name) { name = "Mr. " + name; return name; } } 
0

1 Answer 1

6

Strings are immutable, and passed by value. Every time you create a string, it will never be changed. So unlike instances of classes, you cannot modify a string by handing it to a method which modifies it.

In this case, since you return the modified String in namechanger, all you need to do is make sure you assign myname to the result of that method; like so

myname = namechanger(myname); 

Primitive types (int, float, long, etc) work this way, as do struct instances - so be sure to look for that in the future, if you're ever unsure why a struct's value is not changing when you pass it into a method.

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

9 Comments

All types work this way, not just primitive types...
Maybe in a pedantic sense, but calling a method with class vs struct passes wildly different values - one a pointer, one a whole struct. "Pass by value" and "pass by reference" are terms used to distinguish that behavior difference.
The reference to the string is passed by value, really. It's a reference to the same string, not like passing, say, a DateTime, where inside the function it's a different instance of DateTime.
@Knetic, that's NOT pass by value and pass by reference. "ref" or "out" is what makes something pass by reference. If you don't include that, it's pass by value. See: blogs.msdn.microsoft.com/csharpfaq/2004/03/11/…
@Knetic - I'm not confused at all. There are two competing concepts here - reference/value types versus passing by reference/value. They are two different concepts. The question revolves around passing by value - it has nothing to do with reference/value types. Aquinas was correct in saying that all types work this way.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.