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
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;
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 (
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.