Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

265
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda