Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use the ref or out keyword here?

I have an object that may be null, which I will pass to a method that will set its properties.

So my code looks like:

User user = null;  // may or may not be null at this point.

SetUserProperties(user);

UpdateUser(user);


public void SetUserProperties(User user)
{
      if(user == null) 
          user = new User();

     user.Firstname = "blah";
     ....

}

So I am updating the same object I pass into SetUserProperties.

Should I use the 'ref' keyword in my method SetUserProperties?

like image 218
Blankman Avatar asked Jan 22 '23 08:01

Blankman


2 Answers

I think that 'ref' fits the semantics of what you are trying to do here better.

I, however, try to avoid the 'out' and 'ref' keywords if possible.

Does this suit your needs? It doesn't use either and is a little bit more clear in what it is doing, IMO.

user = user ?? new User();

SetUserProperties(user);

UpdateUser(user);
like image 132
John Gietzen Avatar answered Jan 26 '23 00:01

John Gietzen


It's important to be aware of the difference between an object and a variable:

  • You want the caller's variable to be updated to refer to a new object in some cases, so you need pass by reference semantics. That means you need ref or out
  • You need to read the existing value of the variable to know whether to create a new object or not. That means you need ref rather than out. If you changed it to an out parameter, your if statement wouldn't compile, because user wouldn't be definitely assigned at the start of the method.

Personally I'm not sure this is a nice design, however. Are you sure that it makes sense for the method to create the new object? Can you not do that at the call site? It feels slightly awkward as it is.

Another alternative to using ref (but still potentially creating a new user within the method) would be to return the appropriate reference:

user = SetUserProperties(user);

...

public User SetUserProperties(User user)
{
    if(user == null) 
    {
        user = new User();
    }
    user.Firstname = "blah";
    ....
    return user;
}
like image 24
Jon Skeet Avatar answered Jan 26 '23 01:01

Jon Skeet