Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method returning same object which was passed as parameter

Tags:

methods

c#

oop

Is it acceptable practice to pass an object into a method, then return the same object rather than creating a new object inside of the method itself?

As an example: if have an entity class as follows:

class UserDetails {
    int UserID { get; set; }
    string UserName { get; set; }
    string UserAge { get; set; }
}

And then I pass an instance of this class to a method, as follows:

UserDetails UserInfo = new UserDetails();
UserInfo = Get_Details(UserInfo);

Is it reasonable for the method to do the following?

public UserDetails Get_Details(UserDetails user) {
    // SQL Operations...
    user.age = 32;
    return user;
}
like image 828
punter Avatar asked Apr 03 '13 07:04

punter


1 Answers

IMO, there is no need to return the object. Since it is passed to the method by reference, the caller already has a reference to the same object (with the updated values after the method completes).

On the other hand, what can be useful in some situations is a fluent-interface, where instance-methods of a class return the instance again, e.g:

class X
{
  public X DoThis(int number)
  {
    // do something
    return this;
  }
  public X DoThat(string name)
  {
    // do something else
    return this;
  }
}

This allows to write very readable code, such as:

var x = new X().DoThis(23).DoThat("asdf");
like image 56
M4N Avatar answered Oct 14 '22 13:10

M4N