CodeYun
CodeYun

Reputation: 749

Reference Value Parameter VS Return value which one is good?

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;
       }

Upvotes: 4

Views: 307

Answers (6)

Andras Vass
Andras Vass

Reputation: 11638

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.

Upvotes: 3

Jamie Ide
Jamie Ide

Reputation: 49261

The first method. The second doesn't make any sense; without examining the code (or documentation) there's no way to know that it returns the same instance of UserInfo that is passed in.

Upvotes: 0

Vitaly
Vitaly

Reputation: 2585

You can even have

UserInfo ui = new UserInfo {UserName = "User Name", ...}

(in C# 3.0). But in general, if this is a reference-type, don't instantiate it every time, unless it's really needed (like for System.String)- I'm talking about 2nd example.

Upvotes: 0

Mark Seemann
Mark Seemann

Reputation: 233150

Flippant answer: None of them are good. This is:

UserInfo newUser = New UserInfo(); 
newUser.Modify();

or, if UserInfo is better modeled as a Value Object:

UserInfo newUser = New UserInfo();
var u = newUser.Modify();

although in the latter case, I'd probably name the method something else.

Upvotes: 0

Alex F
Alex F

Reputation: 43311

First method is OK. This is not reference parameter, passing by reference is: ref UserInfo userInfo, and it is not recommended. One of FxCop rules is: Do not pass types by reference, but this is not what you do.

Upvotes: 0

Justin Ethier
Justin Ethier

Reputation: 134167

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.

Upvotes: 5

Related Questions