What Is ref and out In C-Sharp

Author : Sachin Sharma
Published On : 21 Nov 2024
Tags: c#

In c# ref and out keyword used to pass parameters by reference.But there is difference between them.

1) ref Keyword

  • Ref keyword used to pass parameter as reference.
  • Any changes to the parameter made in the method will affect the value outside the method also.
  • The parameter must be intialized before being passed to method.
  • The method can read and modify the parameter value.

class Program
    {
        static void Main()
        {
            int x = 50;
            Console.WriteLine($"Before: x = {x}");
            Add(ref x);  // Passing by reference
            Console.WriteLine($"After: x = {x}");
        }
        static void Add(ref int number)
        {
            number = number + 10;  // Modifying the value
        }
    }

Output : 
    Before: x = 50
    After: x = 60

2) out Keyword

  • out keyword also used to pass parameter as reference. 
  • out is generally used to return multiple values from method.
  • no need to initialize out parameter before being passed to the method.
  • required to assign a value to the out parameter in method.

class Program
        {
            static void Main()
            {
                int x;        
                Add(out x);  
                Console.WriteLine($"x = {x}");
            }
            static void Add(out int number)
            {
                number = 40 + 5;  // Modifying the value
            }
        } 

 

Comments

No comments have been added to this article.

Add Comment