Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference Value Parameter VS Return value which one is good?

Tags:

c#

When we want to modify some value in one object we may use two different methods, just want to know which one is better or there is no big different between them.

    1.
  

void SomeMethod()
   {
      UserInfo newUser = New UserInfo();
      ModifyUserInfo(newUser);
      //Modify UserInfo after calling void method GetUserInfo
   }




           void ModifyUserInfo(UseerInfo userInfo)
           {
               userInfo.UserName = "User Name";
               .....
           }
    2.
  
    void SomeMethod()
       {
          UserInfo newUser = New UserInfo();
          //Assign new userinfo explicitly
          newUser = GetUserInfo(newUser);

       }


       UserInfo ModifyUserInfo(UseerInfo userInfo)
       {
           userInfo.UserName = "User Name";
           .....
           return userInfo;
       }
like image 723
CodeYun Avatar asked Feb 28 '23 08:02

CodeYun


2 Answers

I would prefer a third:

   void SomeMethod()
   {
      UserInfo newUser = GetUserInfo();
   }


   UserInfo GetUserInfo()
   {
       UserInfo userInfo = New UserInfo();
       userInfo.UserName = "User Name";
       .....
       return userInfo;
   }

Basically this lets GetUserInfo handle all of the details of building up UserInfo, and your calling code does not have to worry about any of the details other than the object it is getting back.

like image 97
Justin Ethier Avatar answered Mar 01 '23 20:03

Justin Ethier


From the second signature - UserInfo ModifyUserInfo(UseerInfo userInfo) -, I might assume that it will treat UserInfo as if it was immutable.

I might be mislead into thinking that it will make a copy of the object passed in, and return a new, modified one.

like image 40
Andras Vass Avatar answered Mar 01 '23 21:03

Andras Vass