I have a method that I will use in the following contexts:
1.
User user = null;
if(...)
{
user = defaultUser;
SetUser(a,b,user);
}
else
{
SetUser(a,b,user);
}
SaveUser(user);
So some cases are where user may be null, while in other cases it will already be initialized.
How should I design the SetUser method?
I currently have it like so, but this causes an error when user is null.
public void SetUser(object a, object b, User user)
{
if(user == null)
user = new User();
user.Security = a.security;
user.Blah = b.type;
}
Neither. Just return it:
Send in a user object or null, and assign the result to the reference:
Note that you have to create a new
defaultUserinstance each time you use it, as it will become the new user object. If you try to reuse the default user object, you will end up overwriting previous user objects and also end up with several references to the same object instead of separate objects.