I was reading a code that made me stop at some line:
List<object> props = new List<object>();
DoWork(param1, param2, props);
//props.Count grew up
I was thinking that changing a variable outside its scope requires passing it as out
or ref
, but then I realized that unless the DoWork
method changes the props
reference like:
props = new List<object>();
the reference will be point to the same location. So there is no need to use ref
here.
and then I created a method for string
type:
static void ChangeMe(string str)
{
str = "W77";
}
public static void Main(string[] args)
{
string str = "p1";
ChangeMe(str);
//str is still "p1"
}
If the behavior motivated the List to be changed outside its scope is that it's reference type, why string
doesn't change if it's not reallocated in the callee method and it's a reference type like List<object>
?