Wednesday, November 28, 2018

ref Keyword Vs out Keyword


ref Keyword Vs out Keyword
The ref modifier means that:
  1. The value is already set and
  2. The method can read and modify it.
The out modifier means that:
  1. The Value isn't set and can't be read by the method until it is set.
  2. The method must set it before returning.

Ref

The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.

Out

The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it. An argument that is passed using an out keyword must be initialized in the called method before it returns back to calling method.

Program with ref and out keyword

  1. public class Example
  2. {
  3. public static void Main() //calling method
  4. {
  5. int val1 = 0; //must be initialized
  6. int val2; //optional
  7.  
  8. Example1(ref val1);
  9. Console.WriteLine(val1); // val1=1
  10.  
  11. Example2(out val2);
  12. Console.WriteLine(val2); // val2=2
  13. }
  14.  
  15. static void Example1(ref int value) //called method
  16. {
  17. value = 1;
  18. }
  19. static void Example2(out int value) //called method
  20. {
  21. value = 2; //must be initialized
  22. }
  23. }
  24.  
  25. /* Output
  26. 1
  27. 2
  28. */

Note


  1. Do not be confused with the concept of passing by reference and the concept of reference type. These two concepts are not the same.
  2. A value type or a reference type can be passed to method parameter by using ref keyword. There is no boxing of a value type when it is passed by reference.
  3. Properties cannot be passed to ref or out parameters since internally they are functions and not members/variables.

No comments:

Post a Comment

ref Keyword Vs out Keyword

ref Keyword Vs out Keyword The  ref  modifier means that: The value is already set and The method can read and modify it. The  ou...