The method returns the same object that was passed as a parameter

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

As an example: if there is 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 the method as follows:

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

Can the method be used as follows?

public UserDetails Get_Details(UserDetails user) {
    // SQL Operations...
    user.age = 32;
    return user;
}
+5
source share
7 answers

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

, , , - , - , :

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

, :

var x = new X().DoThis(23).DoThat("asdf");
+2

( ).

:

class FooBuilder {
  FooBuilder WithAge(int age);
  FooBuilder WithUrl(Url url);

  Foo ToFoo();
}

new FooBuilder().WithAge(12).WithUrl(new Url("http://www.happybirthday.com/").ToFoo();

.

new User { Age = 45, UserName = "Bob", Id = 101 };
+1

, ;

  • get, , load .
  • UserDetails, , id. .
  • , .. .
+1

, , , . ref,

public void Get_Details(ref UserDetails user)
{
    // SQL Operations. . .
    user.age= 32;
}

, , , . . . .

0

OOD. , .

public UserDetailsProjection GetDetailsByUserId(Guid userID)
{
   // Code goes here
   return user;
}

: ref , .

0

, , , .

:

UserInfo = Get_Details(UserInfo);

, , :

Get_Details(UserInfo);

, - , , .

, :

UserInfo.Get_Details();

, , :

class UserDetails {

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

  public UserDetails() {
    Get_Details(this);
  }

}

, :

UserDetails UserInfo = new UserDetails();
0

. .

public class SomeClass
{
    public string Field_1;
    public int Field_2;

    public SomeClass(int ID)
    {
        // Sql operations by ID or another value
        // set fields
    }

    public AnotherMethod(int ID)
    {
        // Sql operations by ID or another value
        // set fields
    }
}
0

All Articles