In a C # program, I created a method that removes an object from a list. The user enters the index of the item to delete, then the user is prompted to confirm the removal, and the item is removed from the list if the user confirms, otherwise the list remains unchanged.
I am not sure of the best way to pass arguments to a 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 does not work as I am getting errors. The use of the unrecognized local variable clients and the out parameter for the out parameter must be assigned before the control leaves the current method. I thought I could pass the list by value and return the same list, for example:
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; }
but this does not seem effective, since the same variable is passed by value and then returned.
What is the most efficient way to pass arguments in this case?
source share