Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

266
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda