In a C# program I've made a method that deletes an object from a list. The user enters the index of the item to be deleted, the user is then asked to confirm the deletion, and the item is removed from the list if the user confirms, otherwise the list remains the same.
I'm not sure about the best way to pass arguments to the method. I tried passing the list by reference (as an out
parameter):
static void DeleteCustomer(out List<Customer> customers)
{
// ...display list of objects for user to choose from...
int deleteId = ReadInt("Enter ID of customer to delete: ");
Console.Write("Are you sure you want to delete this customer?");
if (Console.ReadLine().ToLower() == "y")
{
customers.RemoveAt(deleteId);
}
}
The above code doesn't work as I get the errors Use of unassigned local variable 'customers' and The out parameter 'customers' must be assigned to before control leaves the current method. I was thinking I could pass the list by value and return the same list, like this:
static List<Customer> DeleteCustomer(List<Customer> customers)
{
int deleteId = ReadInt("Enter ID of customer to delete: ");
Console.Write("Are you sure you want to delete this customer?");
if (Console.ReadLine().ToLower() == "y")
{
customers.RemoveAt(deleteId);
}
return customers;
}
// ...which would be called from another method with:
List<Customer> customers = DeleteCustomer(customers);
but this doesn't seem efficient as the same variable is passed by value and then returned.
What is the most efficient way to pass arguments in this case?