I'm trying to understand the following mechanism.
List<string> list = new List<string>();
list.Add("test");
NewLines(list);
Console.WriteLine(list.Count) // result is 1 not 0
ClearLines(list);
Console.WriteLine(list.Count) // result is 0
private static void NewLines(List<string> lines)
{
lines = new List<string>();
}
private static void ClearLines(List<string> lines)
{
lines.Clear();
}
If arguments in C# are passed by reference then why is the list not empty after calling NewLines(list);?
Arguments are always passed by value unless the ref or out keyword is used. what's potentially confusing is that list is a reference (becasue List<T> is a reference type). So when you pass in list, you're passing in the value of the reference. If you change it's value within the function, it's still just changing the local variable to a new list - it doesn't affect the passed-in variable.
So the change to get the code to behave how you expect is just to add the ref keyword:
private static void NewLines(ref List<string> lines)
{
lines = new List<string>();
}
Although I would note that returning values is preferred compared to ref keywords