user2461687 user2461687 - 3 months ago 17
C# Question

Convert method to and object c#

I would like to convert this method into an object because I use it many times, and the only things that changes is the field "coleccion5", the one inside the foreach loop and in the return.

public AutoCompleteStringCollection Auto_telefono()
{
DataTable dt = Datos();
//recorrer y cargar los items para el autocompletado
int cantidad = dt.Rows.Count;
int contados = 0;
foreach (DataRow row in dt.Rows)
{
coleccion5.Add(Convert.ToString(row["telefono"]));
contados++;
progressBar1.Value = contados / cantidad * 30 + 70;
}
return coleccion5;
}//fin metodo de llenado de autocompletado

Answer

If coleccion5 is the only thing changing, then pass it as parameter

public void Auto_telefono(AutoCompleteStringCollection coleccion)
{
    DataTable dt = Datos();
    //recorrer y cargar los items para el autocompletado
    int cantidad = dt.Rows.Count;
    int contados = 0;
    foreach (DataRow row in dt.Rows)
    {
        coleccion.Add(Convert.ToString(row["telefono"]));
        contados++;
        progressBar1.Value = contados / cantidad * 30 + 70;
    }
}

And call it with

Auto_telefono(coleccion5);

Note also that you don't need to return the collection, since what you are passing as a parameter is a reference to the collection, not the collection object itself, because the AutoCompleteStringCollection class (and in fact all the classes) are reference types.

var coleccion5 = new AutoCompleteStringCollection();
Auto_telefono(coleccion5);
// Now coleccion5 contains the added entries, no assignement to it needed.