Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

264
Views
Assigning a value to a List passed by reference

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);?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!