Should I use the ref or out keyword here?

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

So my code looks like this:

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 that I pass to SetUserProperties.

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

+4
source share
5 answers

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

However, I try to avoid the keywords "out" and "ref", if possible.

Does this fit your needs? It is also not used and is a bit clearer in what it does, IMO.

 user = user ?? new User(); SetUserProperties(user); UpdateUser(user); 
+5
source

It is important to know the difference between an object and a variable:

  • You want the caller variable to be updated to refer to a new object in some cases, so you need to go through the reference semantics. That means you need ref or out
  • You need to read the existing value of the variable to find out whether to create a new object or not. That means you need ref , not out . If you change it to the out parameter, your if will not compile because user will not be specifically assigned at the beginning of the method.

Personally, I'm not sure if this is a nice design. Are you sure that the method of creating a new object makes sense? Can you do it on the site? It feels a little awkward as it is.

Another alternative to using ref (but potentially creating a new user in this method) would be to return the corresponding link:

 user = SetUserProperties(user); ... public User SetUserProperties(User user) { if(user == null) { user = new User(); } user.Firstname = "blah"; .... return user; } 
+5
source

You would use ref, since you have the ability to point the variable to a new object in memory. If you used, you will need to change the user.

0
source

ref = You want the function to have a handle to the object and potentially "redirect it to another location in memory" (that is, set it for another instance of this type of object)

out = You need a way to "redirect it to another location in memory"

0
source

Yes, you should use ref . The out keyword refers to uninitialized variables, which is not the case here.

-1
source

Source: https://habr.com/ru/post/1305687/


All Articles