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