Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# should I pass a parameter by value and return the same variable, or pass by reference?

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?

like image 954
Ruben9922 Avatar asked Dec 02 '14 18:12

Ruben9922


1 Answers

List like all reference types, is passed as a reference to the object, and not a copy of it.

Note that this is very different from saying it is passed by reference, as that would imply assignment of the parameter propagates to the caller, which it does not

It does means that modifications to the object (such as those performed by RemoveAt) will automatically propagate to the caller.

Thus, just pass it; no need for a return value or out/ref parameters.

You will very rarely use out/ref for reference types, and when used for value types, the performance difference will be so small versus returning that you shouldn't worry about it unless you have profiled and made sure that the problem occurs there. Use what makes the most idiomatic sense.

like image 98
BradleyDotNET Avatar answered Nov 14 '22 22:11

BradleyDotNET