I’ve got a philosophical programming problem. Let’s say I have a class named Employees. Employees has business members that get set from a dataTable. In order to fill this, I use a method that takes an instance of the employee class, loops through a dataTable, and sets the members of the instance passed into it. For instance:
public void GetEmployees(objEmployee) { //the function I am calling returns a dataTable of all the employees in the db. dim dt as DataTable = dbEmployees.GetEmployees(); foreach(DataRow drow in dt.rows) { objEmployee.Name = drow['Name'].ToString(); objEmployee.ID = drow['ID'].ToString(); } }
Then I would call the code like this in my UI logic:
public void GetEmployees() { Employees employee = new Employees(); employee.GetEmployees(employee); }
My question is, is it acceptable to pass in my class instance into a method and change the properties like I am doing, or would it be more object-oriented to do it through a function like this:
public Employees GetEmployees() { Employees objEmployee = new Employees(); //the function I am calling returns a dataTable of all the employees in the db. dim dt as DataTable = dbEmployees.GetEmployees(); foreach(DataRow drow in dt.rows) { objEmployee.Name = drow['Name'].ToString(); objEmployee.ID = drow['ID'].ToString(); } return objEmployee }
And then I would call it like this:
private void GetEmployees() { Employees employee; employee = employee.GetEmployees(); }
Is there any advantage of using a function over a method? Thanks!
Both things are methods (also known as functions). The difference is that the first one ‘returns by reference’ while the second one ‘returns a reference’.
There is no advantage in returning by reference in C# because in the simpler, natural case where you merely return a reference, no copying is done (unlike in C++).
Returning a reference is, thus, to be always preferred as it’s the easiest, and it allows great syntactic flexibility at the call site (such as nesting expressions: manager.Fire(GetEmployee()) without the need for a separate statement).