O. Watson O. Watson - 1 year ago 62
C# Question

C# - Why is this variable not being changed after being put through a method

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;


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download