C# Lessons

Ref vs out #L5

Another short post about ref and out – keywords that are used to pass parameters to functions.
Using them we have to also remember that in both cases, the parameters are passed as references (address) and not values.

Ref

  • In the case of ref, the variable must be initialized before passing it as a parameter.
  • With ref, assigning a value to a variable in the function isn’t required before returning to the calling function.
  • So simply: ref means that the passed parameter has an assigned value that can be read or changed in the called function.

Out

  • In the case of out, it’s not required for variable to be initialized before being passed as a parameter.
  • In the called method, the value of the passed variable must be initialized before returning to the calling function.
  • So simply: out means that the passed parameter has no value assigned and must be assigned in the called function.

And that’s all!
It’s also good to remember that out is often used when we want the function to return more than one parameter (out as input doesn’t accept any value).

Leave a Reply