below is some very simple code that will highlight my problem/question
static void Main(string[] args)
{
var myInitialString = "My Initial String";
Console.WriteLine($"{nameof(myInitialString)}: {myInitialString}");
MyMethod(myInitialString, MyRefMethod(ref myInitialString));
Console.ReadLine();
}
static void MyMethod(string myVariableString, string otherString)
{
//Prints out "My Initial String"
Console.WriteLine($"MyString in myMethod: {myVariableString}");
}
static string MyRefMethod(ref string myRefString)
{
myRefString = "MyEdittedString";
Console.WriteLine($"{nameof(myRefString)} = {myRefString}");
return "OtherString";
}
If I debug this and put a watch on myInitialString
I can see that its value is "My Editted String"
just before it goes into MyMethod
and remains at that value. However the myVariableString
argument has the value of "My Initial String"
. This seems to imply that the variable value had been captured before the second parameter, which is a method had been evaluated.
If I make a call to the MyRefMethod
seperately before calling MyMethod
, it works as I'd expect, it prints "My Editted String"
. If I swap the arguments so the call to MyRefMethod
represents the first argument passed to MyMethod
, it also prints out "My Editted String"
.
Which leads me to my question: How and when are the arguments that are passed to a method captured? Is the behavior displayed above to be expected?
Edit: Just to clarify as the question has been marked a duplicate potentially. This isn't a question about the difference between reference and value types and passing them around. As someone has pointed out below, this behavior would be the same with a value type