开发者

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 pa开发者_运维问答ss into SetUserProperties.

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


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


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


You would use ref since you have the potential to point the variable to a new object in memory. If you used out, you would be required to change user.


ref = You want to have the function have a handle to the object, and potentially "redirect it to another location in memory" (i.e. set it to a different instantiation of that object type)

out = You require the method to "redirect it to another location in memory"


Yes, you should use ref. The out keyword is for uninitialized variables, which isn't the case here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜