General short guide for passing method parameters by ref or by value (C #)?

Something like:

  • if the value of a variable after a method call should be returned:
  • if it can be created before calling the ref method
  • if you do not need to instantiate before using the call

  • if the variable value is used to return, make a decision or calculate other values โ€‹โ€‹from a method call, do not use ref no out

Did I understand correctly? What is your brief recommendation?

+6
methods parameter-passing c # parameters
source share
3 answers

For value types:

  • If you just want to use the value contained and NOT changing it in the original place, use the default transfer method (by value)
  • If you need to change it in the original store, use ref. Example:

    int a = -3; protected void EnsurePositiveValues(ref int value) { if (value < 0) value = 0; } 

For reference types:

  • If you just need to use the instance or change it, use the default transfer method (by reference, should be called "by reference")
  • If you need to (re) assign in the source link, use ref. Example:

     User u = MembershipAPI.GetUser(312354); protected void EnsureUser(ref User user) { if (user == null) user = new User(); } 
+4
source share

You also need to consider values โ€‹โ€‹and reference types. When you pass a reference type to a method as a parameter, you pass a pointer to a variable. This means that inside the method you can make changes to the variable, and they will be available for the code that called the method, however, if you set it to null, you only set the pointer to zero, and the variable will be intact when your method returns.

+1
source share

Not sure if this really answers your question, but one good use of passing a value by reference (using the out keyword) that I found is ...

 int i = 0; if (int.TryParse("StringRepresentation", out i) { // do something with i which has taken the value of a the previous successful TryParse } 
0
source share

All Articles