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?
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:
ref
or out
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With